repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNameParser.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNameParser.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable End Function End Class End Namespace
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/Pia1.dll
MZ@ !L!This program cannot be run in DOS mode. $PELaL! $ @@ @`$K@`  H.text  `.rsrc@@@.reloc ` @B$HP BSJB v4.0.30319lt#~8#Strings#US #GUID0#BlobW %3,1*]>t>>> >   ;;F# F# ((!!)P1 9PA!.3..#~.+C C&T ' <Module>mscorlibI1S1I2NS1S2Sub1xSystemValueTypeF1System.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributePia1Pia1.dll d9GDxN:{Zz\V4    )$27e3e649-994b-4f58-b3c6-f8089a5f2c01 )$27e3e649-994b-4f58-b3c6-f8089a5f2c02TWrapNonExceptionThrows Pia1.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b58257$$ $_CorDllMainmscoree.dll% @0HX@<<4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfox000004b0,FileDescription 0FileVersion0.0.0.04 InternalNamePia1.dll(LegalCopyright < OriginalFilenamePia1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 4
MZ@ !L!This program cannot be run in DOS mode. $PELaL! $ @@ @`$K@`  H.text  `.rsrc@@@.reloc ` @B$HP BSJB v4.0.30319lt#~8#Strings#US #GUID0#BlobW %3,1*]>t>>> >   ;;F# F# ((!!)P1 9PA!.3..#~.+C C&T ' <Module>mscorlibI1S1I2NS1S2Sub1xSystemValueTypeF1System.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributePia1Pia1.dll d9GDxN:{Zz\V4    )$27e3e649-994b-4f58-b3c6-f8089a5f2c01 )$27e3e649-994b-4f58-b3c6-f8089a5f2c02TWrapNonExceptionThrows Pia1.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b58257$$ $_CorDllMainmscoree.dll% @0HX@<<4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfox000004b0,FileDescription 0FileVersion0.0.0.04 InternalNamePia1.dll(LegalCopyright < OriginalFilenamePia1.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 4
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/MethodDocumentationCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public MethodDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"namespace Acme { struct ValueType { public void M(int i) { } public static explicit operator ValueType (byte value) { return default(ValueType); } } class Widget: IProcess { public class NestedClass { public void M(int i) { } } /// <summary>M0 Summary.</summary> public static void M0() { } public void M1(char c, out float f, ref ValueType v) { } public void M2(short[] x1, int[,] x2, long[][] x3) { } public void M3(long[][] x3, Widget[][,,] x4) { } public unsafe void M4(char *pc, Color **pf) { } public unsafe void M5(void *pv, double *[][,] pd) { } public void M6(int i, params object[] args) { } public void M7((int x1, int x2, int x3, int x4, int x5, int x6, short x7) z) { } public void M8((int x1, int x2, int x3, int x4, int x5, int x6, short x7, int x8) z) { } public void M9((int x1, int x2, int x3, int x4, int x5, int x6, short x7, (string y1, string y2)) z) { } public void M10((int x1, short x2) y, System.Tuple<int, short> z) { } } class MyList<T> { public void Test(T t) { } public void Zip(MyList<T> other) { } public void ReallyZip(MyList<MyList<T>> other) { } } class UseList { public void Process(MyList<int> list) { } public MyList<T> GetValues<T>(T inputValue) { return null; } } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestMethodInStruct() { Assert.Equal("M:Acme.ValueType.M(System.Int32)", _acmeNamespace.GetTypeMembers("ValueType").Single().GetMembers("M").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { Assert.Equal("M:Acme.Widget.NestedClass.M(System.Int32)", _widgetClass.GetTypeMembers("NestedClass").Single().GetMembers("M").Single().GetDocumentationCommentId()); } [Fact] public void TestStaticMethod() { var m0 = _widgetClass.GetMembers("M0").Single(); Assert.Equal("M:Acme.Widget.M0", m0.GetDocumentationCommentId()); Assert.Equal( @"<member name=""M:Acme.Widget.M0""> <summary>M0 Summary.</summary> </member> ", m0.GetDocumentationCommentXml()); } [Fact] public void TestMethodWithRefAndOut() { Assert.Equal("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)", _widgetClass.GetMembers("M1").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithArrays1() { Assert.Equal("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])", _widgetClass.GetMembers("M2").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithArrays2() { Assert.Equal("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])", _widgetClass.GetMembers("M3").Single().GetDocumentationCommentId()); } [Fact] public void TestUnsafe1() { Assert.Equal("M:Acme.Widget.M4(System.Char*,Color**)", _widgetClass.GetMembers("M4").Single().GetDocumentationCommentId()); } [Fact] public void TestUnsafe2() { Assert.Equal("M:Acme.Widget.M5(System.Void*,System.Double*[0:,0:][])", _widgetClass.GetMembers("M5").Single().GetDocumentationCommentId()); } [Fact] public void TestParams() { Assert.Equal("M:Acme.Widget.M6(System.Int32,System.Object[])", _widgetClass.GetMembers("M6").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength7() { Assert.Equal("M:Acme.Widget.M7(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16})", _widgetClass.GetMembers("M7").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength8() { Assert.Equal("M:Acme.Widget.M8(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16,System.ValueTuple{System.Int32}})", _widgetClass.GetMembers("M8").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength9() { Assert.Equal("M:Acme.Widget.M9(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16,System.ValueTuple{System.ValueTuple{System.String,System.String}}})", _widgetClass.GetMembers("M9").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength2() { Assert.Equal("M:Acme.Widget.M10(System.ValueTuple{System.Int32,System.Int16},System.Tuple{System.Int32,System.Int16})", _widgetClass.GetMembers("M10").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodInGenericClass() { Assert.Equal("M:Acme.MyList`1.Test(`0)", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("Test").Single().GetDocumentationCommentId()); } [WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")] [Fact] public void TestMethodWithGenericDeclaringTypeAsParameter() { Assert.Equal("M:Acme.MyList`1.Zip(Acme.MyList{`0})", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("Zip").Single().GetDocumentationCommentId()); } [WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")] [Fact] public void TestMethodWithGenericDeclaringTypeAsTypeParameter() { Assert.Equal("M:Acme.MyList`1.ReallyZip(Acme.MyList{Acme.MyList{`0}})", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("ReallyZip").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithClosedGenericParameter() { Assert.Equal("M:Acme.UseList.Process(Acme.MyList{System.Int32})", _acmeNamespace.GetTypeMembers("UseList").Single().GetMembers("Process").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericMethod() { Assert.Equal("M:Acme.UseList.GetValues``1(``0)", _acmeNamespace.GetTypeMembers("UseList").Single().GetMembers("GetValues").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithMissingType() { var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; var compilation = CreateCompilation(references: new[] { csharpAssemblyReference, ilAssemblyReference }, source: @"class C { internal static CSharpErrors.ClassMethods F = null; }"); var type = compilation.Assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); type = (NamedTypeSymbol)type.GetMember<FieldSymbol>("F").Type; var members = type.GetMembers(); Assert.InRange(members.Length, 1, int.MaxValue); foreach (var member in members) { var docComment = member.GetDocumentationCommentXml(); Assert.NotNull(docComment); } } [Fact, WorkItem(530924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530924")] public void TestConversionOperator() { Assert.Equal("M:Acme.ValueType.op_Explicit(System.Byte)~Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetMembers("op_Explicit").Single().GetDocumentationCommentId()); } [WorkItem(4699, "https://github.com/dotnet/roslyn/issues/4699")] [WorkItem(25781, "https://github.com/dotnet/roslyn/issues/25781")] [ConditionalFact(typeof(IsEnglishLocal))] public void GetMalformedDocumentationCommentXml() { var source = @" class Test { /// <summary> /// Info /// <!-- comment /// </summary static void Main() {} } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose)); var main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"<!-- Badly formed XML comment ignored for member ""M:Test.Main"" -->", main.GetDocumentationCommentXml(EnsureEnglishUICulture.PreferredOrNull).Trim()); compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)); main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"<!-- Badly formed XML comment ignored for member ""M:Test.Main"" -->", main.GetDocumentationCommentXml(EnsureEnglishUICulture.PreferredOrNull).Trim()); compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)); main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"", main.GetDocumentationCommentXml().Trim()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public MethodDocumentationCommentTests() { _compilation = CreateCompilationWithMscorlib40AndDocumentationComments(@"namespace Acme { struct ValueType { public void M(int i) { } public static explicit operator ValueType (byte value) { return default(ValueType); } } class Widget: IProcess { public class NestedClass { public void M(int i) { } } /// <summary>M0 Summary.</summary> public static void M0() { } public void M1(char c, out float f, ref ValueType v) { } public void M2(short[] x1, int[,] x2, long[][] x3) { } public void M3(long[][] x3, Widget[][,,] x4) { } public unsafe void M4(char *pc, Color **pf) { } public unsafe void M5(void *pv, double *[][,] pd) { } public void M6(int i, params object[] args) { } public void M7((int x1, int x2, int x3, int x4, int x5, int x6, short x7) z) { } public void M8((int x1, int x2, int x3, int x4, int x5, int x6, short x7, int x8) z) { } public void M9((int x1, int x2, int x3, int x4, int x5, int x6, short x7, (string y1, string y2)) z) { } public void M10((int x1, short x2) y, System.Tuple<int, short> z) { } } class MyList<T> { public void Test(T t) { } public void Zip(MyList<T> other) { } public void ReallyZip(MyList<MyList<T>> other) { } } class UseList { public void Process(MyList<int> list) { } public MyList<T> GetValues<T>(T inputValue) { return null; } } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestMethodInStruct() { Assert.Equal("M:Acme.ValueType.M(System.Int32)", _acmeNamespace.GetTypeMembers("ValueType").Single().GetMembers("M").Single().GetDocumentationCommentId()); } [Fact] public void TestNestedClass() { Assert.Equal("M:Acme.Widget.NestedClass.M(System.Int32)", _widgetClass.GetTypeMembers("NestedClass").Single().GetMembers("M").Single().GetDocumentationCommentId()); } [Fact] public void TestStaticMethod() { var m0 = _widgetClass.GetMembers("M0").Single(); Assert.Equal("M:Acme.Widget.M0", m0.GetDocumentationCommentId()); Assert.Equal( @"<member name=""M:Acme.Widget.M0""> <summary>M0 Summary.</summary> </member> ", m0.GetDocumentationCommentXml()); } [Fact] public void TestMethodWithRefAndOut() { Assert.Equal("M:Acme.Widget.M1(System.Char,System.Single@,Acme.ValueType@)", _widgetClass.GetMembers("M1").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithArrays1() { Assert.Equal("M:Acme.Widget.M2(System.Int16[],System.Int32[0:,0:],System.Int64[][])", _widgetClass.GetMembers("M2").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithArrays2() { Assert.Equal("M:Acme.Widget.M3(System.Int64[][],Acme.Widget[0:,0:,0:][])", _widgetClass.GetMembers("M3").Single().GetDocumentationCommentId()); } [Fact] public void TestUnsafe1() { Assert.Equal("M:Acme.Widget.M4(System.Char*,Color**)", _widgetClass.GetMembers("M4").Single().GetDocumentationCommentId()); } [Fact] public void TestUnsafe2() { Assert.Equal("M:Acme.Widget.M5(System.Void*,System.Double*[0:,0:][])", _widgetClass.GetMembers("M5").Single().GetDocumentationCommentId()); } [Fact] public void TestParams() { Assert.Equal("M:Acme.Widget.M6(System.Int32,System.Object[])", _widgetClass.GetMembers("M6").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength7() { Assert.Equal("M:Acme.Widget.M7(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16})", _widgetClass.GetMembers("M7").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength8() { Assert.Equal("M:Acme.Widget.M8(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16,System.ValueTuple{System.Int32}})", _widgetClass.GetMembers("M8").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength9() { Assert.Equal("M:Acme.Widget.M9(System.ValueTuple{System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int16,System.ValueTuple{System.ValueTuple{System.String,System.String}}})", _widgetClass.GetMembers("M9").Single().GetDocumentationCommentId()); } [Fact] public void TestTupleLength2() { Assert.Equal("M:Acme.Widget.M10(System.ValueTuple{System.Int32,System.Int16},System.Tuple{System.Int32,System.Int16})", _widgetClass.GetMembers("M10").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodInGenericClass() { Assert.Equal("M:Acme.MyList`1.Test(`0)", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("Test").Single().GetDocumentationCommentId()); } [WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")] [Fact] public void TestMethodWithGenericDeclaringTypeAsParameter() { Assert.Equal("M:Acme.MyList`1.Zip(Acme.MyList{`0})", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("Zip").Single().GetDocumentationCommentId()); } [WorkItem(766313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766313")] [Fact] public void TestMethodWithGenericDeclaringTypeAsTypeParameter() { Assert.Equal("M:Acme.MyList`1.ReallyZip(Acme.MyList{Acme.MyList{`0}})", _acmeNamespace.GetTypeMembers("MyList", 1).Single().GetMembers("ReallyZip").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithClosedGenericParameter() { Assert.Equal("M:Acme.UseList.Process(Acme.MyList{System.Int32})", _acmeNamespace.GetTypeMembers("UseList").Single().GetMembers("Process").Single().GetDocumentationCommentId()); } [Fact] public void TestGenericMethod() { Assert.Equal("M:Acme.UseList.GetValues``1(``0)", _acmeNamespace.GetTypeMembers("UseList").Single().GetMembers("GetValues").Single().GetDocumentationCommentId()); } [Fact] public void TestMethodWithMissingType() { var csharpAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.CSharp; var ilAssemblyReference = TestReferences.SymbolsTests.UseSiteErrors.IL; var compilation = CreateCompilation(references: new[] { csharpAssemblyReference, ilAssemblyReference }, source: @"class C { internal static CSharpErrors.ClassMethods F = null; }"); var type = compilation.Assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); type = (NamedTypeSymbol)type.GetMember<FieldSymbol>("F").Type; var members = type.GetMembers(); Assert.InRange(members.Length, 1, int.MaxValue); foreach (var member in members) { var docComment = member.GetDocumentationCommentXml(); Assert.NotNull(docComment); } } [Fact, WorkItem(530924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530924")] public void TestConversionOperator() { Assert.Equal("M:Acme.ValueType.op_Explicit(System.Byte)~Acme.ValueType", _acmeNamespace.GetTypeMembers("ValueType").Single().GetMembers("op_Explicit").Single().GetDocumentationCommentId()); } [WorkItem(4699, "https://github.com/dotnet/roslyn/issues/4699")] [WorkItem(25781, "https://github.com/dotnet/roslyn/issues/25781")] [ConditionalFact(typeof(IsEnglishLocal))] public void GetMalformedDocumentationCommentXml() { var source = @" class Test { /// <summary> /// Info /// <!-- comment /// </summary static void Main() {} } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Diagnose)); var main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"<!-- Badly formed XML comment ignored for member ""M:Test.Main"" -->", main.GetDocumentationCommentXml(EnsureEnglishUICulture.PreferredOrNull).Trim()); compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.Parse)); main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"<!-- Badly formed XML comment ignored for member ""M:Test.Main"" -->", main.GetDocumentationCommentXml(EnsureEnglishUICulture.PreferredOrNull).Trim()); compilation = CreateEmptyCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular.WithDocumentationMode(DocumentationMode.None)); main = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("Main"); Assert.Equal(@"", main.GetDocumentationCommentXml().Trim()); } } }
-1
dotnet/roslyn
54,969
Don't skip suppressors with /skipAnalyzers
Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
mavasani
2021-07-20T03:25:02Z
2021-09-21T17:41:22Z
ed255c652a1e10e83aea9ddf6149e175611abb05
388f27cab65b3dddb07cc04be839ad603cf0c713
Don't skip suppressors with /skipAnalyzers. Skipping suppressors can actually be a breaking change as an unsuppressed warning that could have been suppressed by a suppressor can be escalated to an error with /warnaserror. `skipAnalyzers` flag was only designed to skip diagnostic analyzers, so this PR ensures the same by never skipping suppressors. **NOTE:** First 2 commits in the PR are just cherry-picks from https://github.com/dotnet/roslyn/pull/54915, which fix and unskip existing DiagnosticSuppressor unit tests.
./src/Compilers/VisualBasic/BasicAnalyzerDriver/BasicAnalyzerDriver.projitems
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>e8f0baa5-7327-43d1-9a51-644e81ae55f1</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>BasicAnalyzerDriver</Import_RootNamespace> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)VisualBasicDeclarationComputer.vb" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects> <HasSharedItems>true</HasSharedItems> <SharedGUID>e8f0baa5-7327-43d1-9a51-644e81ae55f1</SharedGUID> </PropertyGroup> <PropertyGroup Label="Configuration"> <Import_RootNamespace>BasicAnalyzerDriver</Import_RootNamespace> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildThisFileDirectory)VisualBasicDeclarationComputer.vb" /> </ItemGroup> <ItemGroup Condition="'$(DefaultLanguageSourceExtension)' != '' AND '$(BuildingInsideVisualStudio)' != 'true'"> <ExpectedCompile Include="$(MSBuildThisFileDirectory)**\*$(DefaultLanguageSourceExtension)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordPrintMembers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The `bool PrintMembers(StringBuilder)` method is responsible for printing members declared /// in the containing type that are "printable" (public fields and properties), /// and delegating to the base to print inherited printable members. Base members get printed first. /// It returns true if the record contains some printable members. /// The method is used to implement `ToString()`. /// </summary> internal sealed class SynthesizedRecordPrintMembers : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordPrintMembers( SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.PrintMembersMethodName, hasBody: true, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var result = (ContainingType.IsRecordStruct || (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() && ContainingType.IsSealed)) ? DeclarationModifiers.Private : DeclarationModifiers.Protected; if (ContainingType.IsRecord && !ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG bool modifiersAreValid(DeclarationModifiers modifiers) { if (ContainingType.IsRecordStruct) { return modifiers == DeclarationModifiers.Private; } if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Private && (modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Protected) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: case DeclarationModifiers.Override: case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetWellKnownType(compilation, WellKnownType.System_Text_StringBuilder, diagnostics, location), annotation), ordinal: 0, RefKind.None, "builder", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { ImmutableArray<Symbol> printableMembers = ContainingType.GetMembers().WhereAsArray(m => isPrintable(m)); if (ReturnType.IsErrorType() || printableMembers.Any(m => m.GetTypeOrReturnType().Type.IsErrorType())) { F.CloseMethod(F.ThrowNull()); return; } ArrayBuilder<BoundStatement> block; BoundParameter builder = F.Parameter(this.Parameters[0]); if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() || ContainingType.IsRecordStruct) { if (printableMembers.IsEmpty) { // return false; F.CloseMethod(F.Return(F.Literal(false))); return; } block = ArrayBuilder<BoundStatement>.GetInstance(); } else { MethodSymbol? basePrintMethod = OverriddenMethod; if (basePrintMethod is null || basePrintMethod.ReturnType.SpecialType != SpecialType.System_Boolean) { F.CloseMethod(F.ThrowNull()); // an error was reported in base checks already return; } var basePrintCall = F.Call(receiver: F.Base(ContainingType.BaseTypeNoUseSiteDiagnostics), basePrintMethod, builder); if (printableMembers.IsEmpty) { // return base.PrintMembers(builder); F.CloseMethod(F.Return(basePrintCall)); return; } else { block = ArrayBuilder<BoundStatement>.GetInstance(); // if (base.PrintMembers(builder)) // builder.Append(", ") block.Add(F.If(basePrintCall, makeAppendString(F, builder, ", "))); } } Debug.Assert(!printableMembers.IsEmpty); for (var i = 0; i < printableMembers.Length; i++) { // builder.Append(", <name> = "); // if previous members exist // builder.Append("<name> = "); // if it is the first member // The only printable members are fields and properties, // which cannot be generic so as to have variant names var member = printableMembers[i]; var memberHeader = $"{member.Name} = "; if (i > 0) { memberHeader = ", " + memberHeader; } block.Add(makeAppendString(F, builder, memberHeader)); var value = member.Kind switch { SymbolKind.Field => F.Field(F.This(), (FieldSymbol)member), SymbolKind.Property => F.Property(F.This(), (PropertySymbol)member), _ => throw ExceptionUtilities.UnexpectedValue(member.Kind) }; // builder.Append((object)<value>); OR builder.Append(<value>.ToString()); for value types Debug.Assert(value.Type is not null); if (value.Type.IsValueType) { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.Call(value, F.SpecialMethod(SpecialMember.System_Object__ToString))))); } else { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendObject), F.Convert(F.SpecialType(SpecialType.System_Object), value)))); } } block.Add(F.Return(F.Literal(true))); F.CloseMethod(F.Block(block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundParameter builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static bool isPrintable(Symbol m) { if (m.DeclaredAccessibility != Accessibility.Public || m.IsStatic) { return false; } if (m.Kind is SymbolKind.Field) { return true; } if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; return !property.IsIndexer && !property.IsOverride && property.GetMethod is not null; } return false; } } internal static void VerifyOverridesPrintMembersFromBase(MethodSymbol overriding, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = overriding.ContainingType.BaseTypeNoUseSiteDiagnostics; if (baseType.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(baseType, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, overriding.Locations[0], overriding, baseType); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The `bool PrintMembers(StringBuilder)` method is responsible for printing members declared /// in the containing type that are "printable" (public fields and properties), /// and delegating to the base to print inherited printable members. Base members get printed first. /// It returns true if the record contains some printable members. /// The method is used to implement `ToString()`. /// </summary> internal sealed class SynthesizedRecordPrintMembers : SynthesizedRecordOrdinaryMethod { public SynthesizedRecordPrintMembers( SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.PrintMembersMethodName, hasBody: true, memberOffset, diagnostics) { } protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics) { var result = (ContainingType.IsRecordStruct || (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() && ContainingType.IsSealed)) ? DeclarationModifiers.Private : DeclarationModifiers.Protected; if (ContainingType.IsRecord && !ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { result |= DeclarationModifiers.Override; } else { result |= ContainingType.IsSealed ? DeclarationModifiers.None : DeclarationModifiers.Virtual; } Debug.Assert((result & ~allowedModifiers) == 0); #if DEBUG Debug.Assert(modifiersAreValid(result)); #endif return result; #if DEBUG bool modifiersAreValid(DeclarationModifiers modifiers) { if (ContainingType.IsRecordStruct) { return modifiers == DeclarationModifiers.Private; } if ((modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Private && (modifiers & DeclarationModifiers.AccessibilityMask) != DeclarationModifiers.Protected) { return false; } modifiers &= ~DeclarationModifiers.AccessibilityMask; switch (modifiers) { case DeclarationModifiers.None: case DeclarationModifiers.Override: case DeclarationModifiers.Virtual: return true; default: return false; } } #endif } protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics) { var compilation = DeclaringCompilation; var location = ReturnTypeLocation; var annotation = ContainingType.IsRecordStruct ? NullableAnnotation.Oblivious : NullableAnnotation.NotAnnotated; return (ReturnType: TypeWithAnnotations.Create(Binder.GetSpecialType(compilation, SpecialType.System_Boolean, location, diagnostics)), Parameters: ImmutableArray.Create<ParameterSymbol>( new SourceSimpleParameterSymbol(owner: this, TypeWithAnnotations.Create(Binder.GetWellKnownType(compilation, WellKnownType.System_Text_StringBuilder, diagnostics, location), annotation), ordinal: 0, RefKind.None, "builder", Locations)), IsVararg: false, DeclaredConstraintsForOverrideOrImplementation: ImmutableArray<TypeParameterConstraintClause>.Empty); } protected override int GetParameterCountFromSyntax() => 1; protected override void MethodChecks(BindingDiagnosticBag diagnostics) { base.MethodChecks(diagnostics); var overridden = OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(ContainingType.BaseTypeNoUseSiteDiagnostics, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, Locations[0], this, ContainingType.BaseTypeNoUseSiteDiagnostics); } } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { ImmutableArray<Symbol> printableMembers = ContainingType.GetMembers().WhereAsArray(m => isPrintable(m)); if (ReturnType.IsErrorType() || printableMembers.Any(m => m.GetTypeOrReturnType().Type.IsErrorType())) { F.CloseMethod(F.ThrowNull()); return; } ArrayBuilder<BoundStatement> block; BoundParameter builder = F.Parameter(this.Parameters[0]); if (ContainingType.BaseTypeNoUseSiteDiagnostics.IsObjectType() || ContainingType.IsRecordStruct) { if (printableMembers.IsEmpty) { // return false; F.CloseMethod(F.Return(F.Literal(false))); return; } block = ArrayBuilder<BoundStatement>.GetInstance(); if (!ContainingType.IsRecordStruct) { var ensureStackMethod = F.WellKnownMethod( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, isOptional: true); if (ensureStackMethod is not null) { block.Add(F.ExpressionStatement( F.Call(receiver: null, ensureStackMethod))); } } } else { MethodSymbol? basePrintMethod = OverriddenMethod; if (basePrintMethod is null || basePrintMethod.ReturnType.SpecialType != SpecialType.System_Boolean) { F.CloseMethod(F.ThrowNull()); // an error was reported in base checks already return; } var basePrintCall = F.Call(receiver: F.Base(ContainingType.BaseTypeNoUseSiteDiagnostics), basePrintMethod, builder); if (printableMembers.IsEmpty) { // return base.PrintMembers(builder); F.CloseMethod(F.Return(basePrintCall)); return; } else { block = ArrayBuilder<BoundStatement>.GetInstance(); // if (base.PrintMembers(builder)) // builder.Append(", ") block.Add(F.If(basePrintCall, makeAppendString(F, builder, ", "))); } } Debug.Assert(!printableMembers.IsEmpty); for (var i = 0; i < printableMembers.Length; i++) { // builder.Append(", <name> = "); // if previous members exist // builder.Append("<name> = "); // if it is the first member // The only printable members are fields and properties, // which cannot be generic so as to have variant names var member = printableMembers[i]; var memberHeader = $"{member.Name} = "; if (i > 0) { memberHeader = ", " + memberHeader; } block.Add(makeAppendString(F, builder, memberHeader)); var value = member.Kind switch { SymbolKind.Field => F.Field(F.This(), (FieldSymbol)member), SymbolKind.Property => F.Property(F.This(), (PropertySymbol)member), _ => throw ExceptionUtilities.UnexpectedValue(member.Kind) }; // builder.Append((object)<value>); OR builder.Append(<value>.ToString()); for value types Debug.Assert(value.Type is not null); if (value.Type.IsValueType) { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.Call(value, F.SpecialMethod(SpecialMember.System_Object__ToString))))); } else { block.Add(F.ExpressionStatement( F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendObject), F.Convert(F.SpecialType(SpecialType.System_Object), value)))); } } block.Add(F.Return(F.Literal(true))); F.CloseMethod(F.Block(block.ToImmutableAndFree())); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } static BoundStatement makeAppendString(SyntheticBoundNodeFactory F, BoundParameter builder, string value) { return F.ExpressionStatement(F.Call(receiver: builder, F.WellKnownMethod(WellKnownMember.System_Text_StringBuilder__AppendString), F.StringLiteral(value))); } static bool isPrintable(Symbol m) { if (m.DeclaredAccessibility != Accessibility.Public || m.IsStatic) { return false; } if (m.Kind is SymbolKind.Field) { return true; } if (m.Kind is SymbolKind.Property) { var property = (PropertySymbol)m; return !property.IsIndexer && !property.IsOverride && property.GetMethod is not null; } return false; } } internal static void VerifyOverridesPrintMembersFromBase(MethodSymbol overriding, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = overriding.ContainingType.BaseTypeNoUseSiteDiagnostics; if (baseType.IsObjectType()) { return; } bool reportAnError = false; if (!overriding.IsOverride) { reportAnError = true; } else { var overridden = overriding.OverriddenMethod; if (overridden is object && !overridden.ContainingType.Equals(baseType, TypeCompareKind.AllIgnoreOptions)) { reportAnError = true; } } if (reportAnError) { diagnostics.Add(ErrorCode.ERR_DoesNotOverrideBaseMethod, overriding.Locations[0], overriding, baseType); } } } }
1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void AddMethod_WithAttributes() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void AddThenModifyMethod() { var source0 = @"class A : System.Attribute { } class C { static void Main() { F1(null); } static object F1(string s1) { return s1; } }"; var source1 = @"class A : System.Attribute { } class C { static void Main() { F2(); } [return:A]static object F2(string s2 = ""2"") { return s2; } }"; var source2 = @"class A : System.Attribute { } class C { static void Main() { F2(); } [return:A]static object F2(string s2 = ""2"") { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Main", "F1", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "s1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F2"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F2"); CheckNames(readers, reader1.GetParameterDefNames(), "", "s2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F2"); CheckNames(readers, reader2.GetParameterDefNames()); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F2 CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyMethod_EmbeddedAttributes() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void AddField() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyProperty() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddProperty() { var source0 = @"class A { object P { get; set; } } class B { }"; var source1 = @"class A { object P { get; set; } } class B { object R { get { return null; } } }"; var source2 = @"class A { object P { get; set; } object Q { get; set; } } class B { object R { get { return null; } } object S { set { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetFieldDefNames(), "<P>k__BackingField"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", "set_P", ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("B.R")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(9, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.PropertyMap), Handle(2, TableIndex.Property), Handle(3, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("A.Q")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("B.S")))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q", "S"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q", "set_S"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(3, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(4, TableIndex.Property, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(6, TableIndex.MethodDef), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(3, TableIndex.Property), Handle(4, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void AddEvent() { var source0 = @"delegate void D(); class A { event D E; } class B { }"; var source1 = @"delegate void D(); class A { event D E; } class B { event D F; }"; var source2 = @"delegate void D(); class A { event D E; event D G; } class B { event D F; event D H; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "A", "B"); CheckNames(reader0, reader0.GetFieldDefNames(), "E"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "add_E", "remove_E", ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("B.F")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "F"); CheckNames(readers, reader1.GetMethodDefNames(), "add_F", "remove_F"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.EventMap), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.MethodSpec)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("A.G")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("B.H")))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G", "H"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G", "add_H", "remove_H"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(16, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(4, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(10, TableIndex.Param, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(11, TableIndex.Param, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(12, TableIndex.Param, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(13, TableIndex.Param, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(7, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(8, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(23, TableIndex.TypeRef), Handle(24, TableIndex.TypeRef), Handle(25, TableIndex.TypeRef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(11, TableIndex.MethodDef), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(10, TableIndex.Param), Handle(11, TableIndex.Param), Handle(12, TableIndex.Param), Handle(13, TableIndex.Param), Handle(15, TableIndex.MemberRef), Handle(16, TableIndex.MemberRef), Handle(17, TableIndex.MemberRef), Handle(18, TableIndex.MemberRef), Handle(19, TableIndex.MemberRef), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.Event), Handle(4, TableIndex.Event), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(7, TableIndex.MethodSemantics), Handle(8, TableIndex.MethodSemantics), Handle(3, TableIndex.AssemblyRef), Handle(3, TableIndex.MethodSpec)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002", "0x02000003"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "A", "B`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N { class D { public static void F() { } } } class C { static void Main() => N.D.F(); }"; var source2 = @" namespace N { class D { public static void F() { } } namespace M { class E { public static void G() { } } } } class C { static void Main() => N.M.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.M.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; diff2.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000004"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(20, TableIndex.TypeRef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(11, TableIndex.MemberRef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.GenericParam), Handle(2, TableIndex.MethodSpec)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000003"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); diff1.VerifyUpdatedTypes("0x02000002"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(2, TableIndex.ModuleRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ModuleRef), Handle(2, TableIndex.ImplMap), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyUpdatedTypes("0x02000002", "0x02000004"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyUpdatedTypes("0x02000002", "0x02000004"); CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff2.EmitResult), "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default)); // R.PrintMembers CheckEncMap(reader1, Handle(19, TableIndex.TypeRef), Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); // Synthesized Main method CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void AddMethod_WithAttributes() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void AddThenModifyMethod() { var source0 = @"class A : System.Attribute { } class C { static void Main() { F1(null); } static object F1(string s1) { return s1; } }"; var source1 = @"class A : System.Attribute { } class C { static void Main() { F2(); } [return:A]static object F2(string s2 = ""2"") { return s2; } }"; var source2 = @"class A : System.Attribute { } class C { static void Main() { F2(); } [return:A]static object F2(string s2 = ""2"") { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Main", "F1", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "s1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F2"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F2"); CheckNames(readers, reader1.GetParameterDefNames(), "", "s2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F2"); CheckNames(readers, reader2.GetParameterDefNames()); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F2 CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyMethod_EmbeddedAttributes() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void AddField() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyProperty() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddProperty() { var source0 = @"class A { object P { get; set; } } class B { }"; var source1 = @"class A { object P { get; set; } } class B { object R { get { return null; } } }"; var source2 = @"class A { object P { get; set; } object Q { get; set; } } class B { object R { get { return null; } } object S { set { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetFieldDefNames(), "<P>k__BackingField"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", "set_P", ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("B.R")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(9, TableIndex.TypeRef), Handle(5, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.PropertyMap), Handle(2, TableIndex.Property), Handle(3, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("A.Q")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("B.S")))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q", "S"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q", "set_S"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(3, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(4, TableIndex.Property, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(6, TableIndex.MethodDef), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(3, TableIndex.Property), Handle(4, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void AddEvent() { var source0 = @"delegate void D(); class A { event D E; } class B { }"; var source1 = @"delegate void D(); class A { event D E; } class B { event D F; }"; var source2 = @"delegate void D(); class A { event D E; event D G; } class B { event D F; event D H; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "A", "B"); CheckNames(reader0, reader0.GetFieldDefNames(), "E"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "add_E", "remove_E", ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("B.F")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "F"); CheckNames(readers, reader1.GetMethodDefNames(), "add_F", "remove_F"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.EventMap), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.MethodSpec)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("A.G")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("B.H")))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G", "H"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G", "add_H", "remove_H"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(16, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(4, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(10, TableIndex.Param, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(11, TableIndex.Param, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(12, TableIndex.Param, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(13, TableIndex.Param, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(7, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(8, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(23, TableIndex.TypeRef), Handle(24, TableIndex.TypeRef), Handle(25, TableIndex.TypeRef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(11, TableIndex.MethodDef), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(10, TableIndex.Param), Handle(11, TableIndex.Param), Handle(12, TableIndex.Param), Handle(13, TableIndex.Param), Handle(15, TableIndex.MemberRef), Handle(16, TableIndex.MemberRef), Handle(17, TableIndex.MemberRef), Handle(18, TableIndex.MemberRef), Handle(19, TableIndex.MemberRef), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.Event), Handle(4, TableIndex.Event), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(7, TableIndex.MethodSemantics), Handle(8, TableIndex.MethodSemantics), Handle(3, TableIndex.AssemblyRef), Handle(3, TableIndex.MethodSpec)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002", "0x02000003"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "A", "B`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N { class D { public static void F() { } } } class C { static void Main() => N.D.F(); }"; var source2 = @" namespace N { class D { public static void F() { } } namespace M { class E { public static void G() { } } } } class C { static void Main() => N.M.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.M.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; diff2.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000004"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(20, TableIndex.TypeRef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(11, TableIndex.MemberRef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.GenericParam), Handle(2, TableIndex.MethodSpec)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; diff1.VerifyUpdatedTypes("0x02000003"); CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; diff1.VerifyUpdatedTypes("0x02000002"); CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); diff1.VerifyUpdatedTypes("0x02000002"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C"); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(2, TableIndex.ModuleRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ModuleRef), Handle(2, TableIndex.ImplMap), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyUpdatedTypes("0x02000002", "0x02000004"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyUpdatedTypes("0x02000002", "0x02000004"); CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff2.EmitResult), "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default)); // R.PrintMembers CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); // Synthesized Main method CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } } }
1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./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 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, 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 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 ""T C1<T>.field"" IL_0013: constrained. ""T"" 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(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 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, 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 32 (0x20) .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 ""T C1<T>.field"" IL_0013: box ""T"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: 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 52 (0x34) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""field1 = "" 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.field1"" IL_0013: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0018: pop IL_0019: ldarg.1 IL_001a: ldstr "", field2 = "" IL_001f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0024: pop IL_0025: ldarg.1 IL_0026: ldarg.0 IL_0027: ldfld ""string C1.field2"" IL_002c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0031: pop IL_0032: ldc.i4.1 IL_0033: 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 41 (0x29) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldstr ""Property = "" 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.Property.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 } "); } [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 CS0404: Cannot apply attribute class 'Goo<T>' because it is generic // [Goo<int>] Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "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] [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 CS0404: Cannot apply attribute class 'Goo<T>' because it is generic // [Goo<int>] Diagnostic(ErrorCode.ERR_AttributeCantBeGeneric, "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
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/WellKnownMember.cs
// Licensed to the .NET Foundation under one or more 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 { // Members of well known types internal enum WellKnownMember { System_Math__RoundDouble, System_Math__PowDoubleDouble, System_Array__get_Length, System_Array__Empty, System_Convert__ToBooleanDecimal, System_Convert__ToBooleanInt32, System_Convert__ToBooleanUInt32, System_Convert__ToBooleanInt64, System_Convert__ToBooleanUInt64, System_Convert__ToBooleanSingle, System_Convert__ToBooleanDouble, System_Convert__ToSByteDecimal, System_Convert__ToSByteDouble, System_Convert__ToSByteSingle, System_Convert__ToByteDecimal, System_Convert__ToByteDouble, System_Convert__ToByteSingle, System_Convert__ToInt16Decimal, System_Convert__ToInt16Double, System_Convert__ToInt16Single, System_Convert__ToUInt16Decimal, System_Convert__ToUInt16Double, System_Convert__ToUInt16Single, System_Convert__ToInt32Decimal, System_Convert__ToInt32Double, System_Convert__ToInt32Single, System_Convert__ToUInt32Decimal, System_Convert__ToUInt32Double, System_Convert__ToUInt32Single, System_Convert__ToInt64Decimal, System_Convert__ToInt64Double, System_Convert__ToInt64Single, System_Convert__ToUInt64Decimal, System_Convert__ToUInt64Double, System_Convert__ToUInt64Single, System_Convert__ToSingleDecimal, System_Convert__ToDoubleDecimal, System_CLSCompliantAttribute__ctor, System_FlagsAttribute__ctor, System_Guid__ctor, System_Type__GetTypeFromCLSID, System_Type__GetTypeFromHandle, System_Type__Missing, System_Type__op_Equality, System_Reflection_AssemblyKeyFileAttribute__ctor, System_Reflection_AssemblyKeyNameAttribute__ctor, System_Reflection_MethodBase__GetMethodFromHandle, System_Reflection_MethodBase__GetMethodFromHandle2, System_Reflection_MethodInfo__CreateDelegate, System_Delegate__CreateDelegate, System_Delegate__CreateDelegate4, System_Reflection_FieldInfo__GetFieldFromHandle, System_Reflection_FieldInfo__GetFieldFromHandle2, System_Reflection_Missing__Value, System_IEquatable_T__Equals, System_Collections_Generic_IEqualityComparer_T__Equals, System_Collections_Generic_EqualityComparer_T__Equals, System_Collections_Generic_EqualityComparer_T__GetHashCode, System_Collections_Generic_EqualityComparer_T__get_Default, System_AttributeUsageAttribute__ctor, System_AttributeUsageAttribute__AllowMultiple, System_AttributeUsageAttribute__Inherited, System_ParamArrayAttribute__ctor, System_STAThreadAttribute__ctor, System_Reflection_DefaultMemberAttribute__ctor, System_Diagnostics_Debugger__Break, System_Diagnostics_DebuggerDisplayAttribute__ctor, System_Diagnostics_DebuggerDisplayAttribute__Type, System_Diagnostics_DebuggerNonUserCodeAttribute__ctor, System_Diagnostics_DebuggerHiddenAttribute__ctor, System_Diagnostics_DebuggerBrowsableAttribute__ctor, System_Diagnostics_DebuggerStepThroughAttribute__ctor, System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, System_Diagnostics_DebuggableAttribute_DebuggingModes__Default, System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations, System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue, System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints, System_Runtime_InteropServices_UnknownWrapper__ctor, System_Runtime_InteropServices_DispatchWrapper__ctor, System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, System_Runtime_InteropServices_CoClassAttribute__ctor, System_Runtime_InteropServices_ComAwareEventInfo__ctor, System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler, System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler, System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, System_Runtime_InteropServices_ComVisibleAttribute__ctor, System_Runtime_InteropServices_DispIdAttribute__ctor, System_Runtime_InteropServices_GuidAttribute__ctor, System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType, System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16, System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, System_Runtime_InteropServices_TypeIdentifierAttribute__ctor, System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString, System_Runtime_InteropServices_BestFitMappingAttribute__ctor, System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, System_Runtime_InteropServices_LCIDConversionAttribute__ctor, System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T, System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, System_Runtime_CompilerServices_ExtensionAttribute__ctor, System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor, System_Runtime_CompilerServices_FixedBufferAttribute__ctor, System_Runtime_CompilerServices_DynamicAttribute__ctor, System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, System_Runtime_CompilerServices_CallSite_T__Create, System_Runtime_CompilerServices_CallSite_T__Target, System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject, System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle, System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData, System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, System_Security_UnverifiableCodeAttribute__ctor, System_Security_Permissions_SecurityAction__RequestMinimum, System_Security_Permissions_SecurityPermissionAttribute__ctor, System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, System_Activator__CreateInstance, System_Activator__CreateInstance_T, System_Threading_Interlocked__CompareExchange, System_Threading_Interlocked__CompareExchange_T, System_Threading_Monitor__Enter, //Monitor.Enter(object) System_Threading_Monitor__Enter2, //Monitor.Enter(object, bool&) System_Threading_Monitor__Exit, System_Threading_Thread__CurrentThread, System_Threading_Thread__ManagedThreadId, Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, Microsoft_CSharp_RuntimeBinder_Binder__Convert, Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, Microsoft_CSharp_RuntimeBinder_Binder__GetMember, Microsoft_CSharp_RuntimeBinder_Binder__Invoke, Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, Microsoft_CSharp_RuntimeBinder_Binder__SetMember, Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean, Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString, Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString, Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString, Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString, Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString, Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString, Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString, Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString, Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString, Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object, Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor, Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State, Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr, Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor, Microsoft_VisualBasic_Embedded__ctor, Microsoft_VisualBasic_CompilerServices_Utils__CopyArray, Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod, Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod, Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32, Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, Microsoft_VisualBasic_CompilerServices_Versioned__CallByName, Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric, Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName, Microsoft_VisualBasic_CompilerServices_Versioned__TypeName, Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName, Microsoft_VisualBasic_Information__IsNumeric, Microsoft_VisualBasic_Information__SystemTypeName, Microsoft_VisualBasic_Information__TypeName, Microsoft_VisualBasic_Information__VbTypeName, Microsoft_VisualBasic_Interaction__CallByName, System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext, System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task, System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, Microsoft_VisualBasic_Strings__AscCharInt32, Microsoft_VisualBasic_Strings__AscStringInt32, Microsoft_VisualBasic_Strings__AscWCharInt32, Microsoft_VisualBasic_Strings__AscWStringInt32, Microsoft_VisualBasic_Strings__ChrInt32Char, Microsoft_VisualBasic_Strings__ChrWInt32Char, System_Xml_Linq_XElement__ctor, System_Xml_Linq_XElement__ctor2, System_Xml_Linq_XNamespace__Get, System_Windows_Forms_Application__RunForm, System_Environment__CurrentManagedThreadId, System_ComponentModel_EditorBrowsableAttribute__ctor, System_Runtime_GCLatencyMode__SustainedLowLatency, System_ValueTuple_T1__Item1, System_ValueTuple_T2__Item1, System_ValueTuple_T2__Item2, System_ValueTuple_T3__Item1, System_ValueTuple_T3__Item2, System_ValueTuple_T3__Item3, System_ValueTuple_T4__Item1, System_ValueTuple_T4__Item2, System_ValueTuple_T4__Item3, System_ValueTuple_T4__Item4, System_ValueTuple_T5__Item1, System_ValueTuple_T5__Item2, System_ValueTuple_T5__Item3, System_ValueTuple_T5__Item4, System_ValueTuple_T5__Item5, System_ValueTuple_T6__Item1, System_ValueTuple_T6__Item2, System_ValueTuple_T6__Item3, System_ValueTuple_T6__Item4, System_ValueTuple_T6__Item5, System_ValueTuple_T6__Item6, System_ValueTuple_T7__Item1, System_ValueTuple_T7__Item2, System_ValueTuple_T7__Item3, System_ValueTuple_T7__Item4, System_ValueTuple_T7__Item5, System_ValueTuple_T7__Item6, System_ValueTuple_T7__Item7, System_ValueTuple_TRest__Item1, System_ValueTuple_TRest__Item2, System_ValueTuple_TRest__Item3, System_ValueTuple_TRest__Item4, System_ValueTuple_TRest__Item5, System_ValueTuple_TRest__Item6, System_ValueTuple_TRest__Item7, System_ValueTuple_TRest__Rest, System_ValueTuple_T1__ctor, System_ValueTuple_T2__ctor, System_ValueTuple_T3__ctor, System_ValueTuple_T4__ctor, System_ValueTuple_T5__ctor, System_ValueTuple_T6__ctor, System_ValueTuple_T7__ctor, System_ValueTuple_TRest__ctor, System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, System_String__Format_IFormatProvider, Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, System_Runtime_CompilerServices_NullableAttribute__ctorByte, System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, System_Runtime_CompilerServices_NullableContextAttribute__ctor, System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor, System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, System_ObsoleteAttribute__ctor, System_Span_T__ctor, System_Span_T__get_Item, System_Span_T__get_Length, System_ReadOnlySpan_T__ctor, System_ReadOnlySpan_T__get_Item, System_ReadOnlySpan_T__get_Length, System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, Microsoft_VisualBasic_Conversion__FixSingle, Microsoft_VisualBasic_Conversion__FixDouble, Microsoft_VisualBasic_Conversion__IntSingle, Microsoft_VisualBasic_Conversion__IntDouble, System_Math__CeilingDouble, System_Math__FloorDouble, System_Math__TruncateDouble, System_Index__ctor, System_Index__GetOffset, System_Range__ctor, System_Range__StartAt, System_Range__EndAt, System_Range__get_All, System_Range__get_Start, System_Range__get_End, System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, System_IAsyncDisposable__DisposeAsync, System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, System_Collections_Generic_IAsyncEnumerator_T__get_Current, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, System_Threading_Tasks_Sources_IValueTaskSource__GetResult, System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, System_Threading_Tasks_ValueTask_T__ctorValue, System_Threading_Tasks_ValueTask__ctor, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, System_Runtime_CompilerServices_ITuple__get_Item, System_Runtime_CompilerServices_ITuple__get_Length, System_InvalidOperationException__ctor, System_Runtime_CompilerServices_SwitchExpressionException__ctor, System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, System_Threading_CancellationToken__Equals, System_Threading_CancellationTokenSource__CreateLinkedTokenSource, System_Threading_CancellationTokenSource__Token, System_Threading_CancellationTokenSource__Dispose, System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, System_Text_StringBuilder__AppendString, System_Text_StringBuilder__AppendChar, System_Text_StringBuilder__AppendObject, System_Text_StringBuilder__ctor, System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear, Count // Remember to update the AllWellKnownTypeMembers tests when making changes here } }
// Licensed to the .NET Foundation under one or more 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 { // Members of well known types internal enum WellKnownMember { System_Math__RoundDouble, System_Math__PowDoubleDouble, System_Array__get_Length, System_Array__Empty, System_Convert__ToBooleanDecimal, System_Convert__ToBooleanInt32, System_Convert__ToBooleanUInt32, System_Convert__ToBooleanInt64, System_Convert__ToBooleanUInt64, System_Convert__ToBooleanSingle, System_Convert__ToBooleanDouble, System_Convert__ToSByteDecimal, System_Convert__ToSByteDouble, System_Convert__ToSByteSingle, System_Convert__ToByteDecimal, System_Convert__ToByteDouble, System_Convert__ToByteSingle, System_Convert__ToInt16Decimal, System_Convert__ToInt16Double, System_Convert__ToInt16Single, System_Convert__ToUInt16Decimal, System_Convert__ToUInt16Double, System_Convert__ToUInt16Single, System_Convert__ToInt32Decimal, System_Convert__ToInt32Double, System_Convert__ToInt32Single, System_Convert__ToUInt32Decimal, System_Convert__ToUInt32Double, System_Convert__ToUInt32Single, System_Convert__ToInt64Decimal, System_Convert__ToInt64Double, System_Convert__ToInt64Single, System_Convert__ToUInt64Decimal, System_Convert__ToUInt64Double, System_Convert__ToUInt64Single, System_Convert__ToSingleDecimal, System_Convert__ToDoubleDecimal, System_CLSCompliantAttribute__ctor, System_FlagsAttribute__ctor, System_Guid__ctor, System_Type__GetTypeFromCLSID, System_Type__GetTypeFromHandle, System_Type__Missing, System_Type__op_Equality, System_Reflection_AssemblyKeyFileAttribute__ctor, System_Reflection_AssemblyKeyNameAttribute__ctor, System_Reflection_MethodBase__GetMethodFromHandle, System_Reflection_MethodBase__GetMethodFromHandle2, System_Reflection_MethodInfo__CreateDelegate, System_Delegate__CreateDelegate, System_Delegate__CreateDelegate4, System_Reflection_FieldInfo__GetFieldFromHandle, System_Reflection_FieldInfo__GetFieldFromHandle2, System_Reflection_Missing__Value, System_IEquatable_T__Equals, System_Collections_Generic_IEqualityComparer_T__Equals, System_Collections_Generic_EqualityComparer_T__Equals, System_Collections_Generic_EqualityComparer_T__GetHashCode, System_Collections_Generic_EqualityComparer_T__get_Default, System_AttributeUsageAttribute__ctor, System_AttributeUsageAttribute__AllowMultiple, System_AttributeUsageAttribute__Inherited, System_ParamArrayAttribute__ctor, System_STAThreadAttribute__ctor, System_Reflection_DefaultMemberAttribute__ctor, System_Diagnostics_Debugger__Break, System_Diagnostics_DebuggerDisplayAttribute__ctor, System_Diagnostics_DebuggerDisplayAttribute__Type, System_Diagnostics_DebuggerNonUserCodeAttribute__ctor, System_Diagnostics_DebuggerHiddenAttribute__ctor, System_Diagnostics_DebuggerBrowsableAttribute__ctor, System_Diagnostics_DebuggerStepThroughAttribute__ctor, System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, System_Diagnostics_DebuggableAttribute_DebuggingModes__Default, System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations, System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue, System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints, System_Runtime_InteropServices_UnknownWrapper__ctor, System_Runtime_InteropServices_DispatchWrapper__ctor, System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, System_Runtime_InteropServices_CoClassAttribute__ctor, System_Runtime_InteropServices_ComAwareEventInfo__ctor, System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler, System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler, System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor, System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, System_Runtime_InteropServices_ComVisibleAttribute__ctor, System_Runtime_InteropServices_DispIdAttribute__ctor, System_Runtime_InteropServices_GuidAttribute__ctor, System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType, System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16, System_Runtime_InteropServices_Marshal__GetTypeFromCLSID, System_Runtime_InteropServices_TypeIdentifierAttribute__ctor, System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString, System_Runtime_InteropServices_BestFitMappingAttribute__ctor, System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, System_Runtime_InteropServices_LCIDConversionAttribute__ctor, System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers, System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T, System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, System_Runtime_CompilerServices_ExtensionAttribute__ctor, System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor, System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32, System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor, System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows, System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor, System_Runtime_CompilerServices_FixedBufferAttribute__ctor, System_Runtime_CompilerServices_DynamicAttribute__ctor, System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, System_Runtime_CompilerServices_CallSite_T__Create, System_Runtime_CompilerServices_CallSite_T__Target, System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject, System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle, System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData, System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture, System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw, System_Security_UnverifiableCodeAttribute__ctor, System_Security_Permissions_SecurityAction__RequestMinimum, System_Security_Permissions_SecurityPermissionAttribute__ctor, System_Security_Permissions_SecurityPermissionAttribute__SkipVerification, System_Activator__CreateInstance, System_Activator__CreateInstance_T, System_Threading_Interlocked__CompareExchange, System_Threading_Interlocked__CompareExchange_T, System_Threading_Monitor__Enter, //Monitor.Enter(object) System_Threading_Monitor__Enter2, //Monitor.Enter(object, bool&) System_Threading_Monitor__Exit, System_Threading_Thread__CurrentThread, System_Threading_Thread__ManagedThreadId, Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, Microsoft_CSharp_RuntimeBinder_Binder__Convert, Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, Microsoft_CSharp_RuntimeBinder_Binder__GetMember, Microsoft_CSharp_RuntimeBinder_Binder__Invoke, Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, Microsoft_CSharp_RuntimeBinder_Binder__SetMember, Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean, Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString, Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString, Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString, Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString, Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString, Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString, Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString, Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString, Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString, Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString, Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar, Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject, Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object, Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean, Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor, Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State, Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr, Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor, Microsoft_VisualBasic_Embedded__ctor, Microsoft_VisualBasic_CompilerServices_Utils__CopyArray, Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod, Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod, Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32, Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError, Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, Microsoft_VisualBasic_CompilerServices_Versioned__CallByName, Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric, Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName, Microsoft_VisualBasic_CompilerServices_Versioned__TypeName, Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName, Microsoft_VisualBasic_Information__IsNumeric, Microsoft_VisualBasic_Information__SystemTypeName, Microsoft_VisualBasic_Information__TypeName, Microsoft_VisualBasic_Information__VbTypeName, Microsoft_VisualBasic_Interaction__CallByName, System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext, System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T, System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine, System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task, System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor, Microsoft_VisualBasic_Strings__AscCharInt32, Microsoft_VisualBasic_Strings__AscStringInt32, Microsoft_VisualBasic_Strings__AscWCharInt32, Microsoft_VisualBasic_Strings__AscWStringInt32, Microsoft_VisualBasic_Strings__ChrInt32Char, Microsoft_VisualBasic_Strings__ChrWInt32Char, System_Xml_Linq_XElement__ctor, System_Xml_Linq_XElement__ctor2, System_Xml_Linq_XNamespace__Get, System_Windows_Forms_Application__RunForm, System_Environment__CurrentManagedThreadId, System_ComponentModel_EditorBrowsableAttribute__ctor, System_Runtime_GCLatencyMode__SustainedLowLatency, System_ValueTuple_T1__Item1, System_ValueTuple_T2__Item1, System_ValueTuple_T2__Item2, System_ValueTuple_T3__Item1, System_ValueTuple_T3__Item2, System_ValueTuple_T3__Item3, System_ValueTuple_T4__Item1, System_ValueTuple_T4__Item2, System_ValueTuple_T4__Item3, System_ValueTuple_T4__Item4, System_ValueTuple_T5__Item1, System_ValueTuple_T5__Item2, System_ValueTuple_T5__Item3, System_ValueTuple_T5__Item4, System_ValueTuple_T5__Item5, System_ValueTuple_T6__Item1, System_ValueTuple_T6__Item2, System_ValueTuple_T6__Item3, System_ValueTuple_T6__Item4, System_ValueTuple_T6__Item5, System_ValueTuple_T6__Item6, System_ValueTuple_T7__Item1, System_ValueTuple_T7__Item2, System_ValueTuple_T7__Item3, System_ValueTuple_T7__Item4, System_ValueTuple_T7__Item5, System_ValueTuple_T7__Item6, System_ValueTuple_T7__Item7, System_ValueTuple_TRest__Item1, System_ValueTuple_TRest__Item2, System_ValueTuple_TRest__Item3, System_ValueTuple_TRest__Item4, System_ValueTuple_TRest__Item5, System_ValueTuple_TRest__Item6, System_ValueTuple_TRest__Item7, System_ValueTuple_TRest__Rest, System_ValueTuple_T1__ctor, System_ValueTuple_T2__ctor, System_ValueTuple_T3__ctor, System_ValueTuple_T4__ctor, System_ValueTuple_T5__ctor, System_ValueTuple_T6__ctor, System_ValueTuple_T7__ctor, System_ValueTuple_TRest__ctor, System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, System_String__Format_IFormatProvider, Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, System_Runtime_CompilerServices_NullableAttribute__ctorByte, System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, System_Runtime_CompilerServices_NullableContextAttribute__ctor, System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor, System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, System_ObsoleteAttribute__ctor, System_Span_T__ctor, System_Span_T__get_Item, System_Span_T__get_Length, System_ReadOnlySpan_T__ctor, System_ReadOnlySpan_T__get_Item, System_ReadOnlySpan_T__get_Length, System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, Microsoft_VisualBasic_Conversion__FixSingle, Microsoft_VisualBasic_Conversion__FixDouble, Microsoft_VisualBasic_Conversion__IntSingle, Microsoft_VisualBasic_Conversion__IntDouble, System_Math__CeilingDouble, System_Math__FloorDouble, System_Math__TruncateDouble, System_Index__ctor, System_Index__GetOffset, System_Range__ctor, System_Range__StartAt, System_Range__EndAt, System_Range__get_All, System_Range__get_Start, System_Range__get_End, System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, System_IAsyncDisposable__DisposeAsync, System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, System_Collections_Generic_IAsyncEnumerator_T__get_Current, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, System_Threading_Tasks_Sources_IValueTaskSource__GetResult, System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, System_Threading_Tasks_ValueTask_T__ctorValue, System_Threading_Tasks_ValueTask__ctor, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, System_Runtime_CompilerServices_ITuple__get_Item, System_Runtime_CompilerServices_ITuple__get_Length, System_InvalidOperationException__ctor, System_Runtime_CompilerServices_SwitchExpressionException__ctor, System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, System_Threading_CancellationToken__Equals, System_Threading_CancellationTokenSource__CreateLinkedTokenSource, System_Threading_CancellationTokenSource__Token, System_Threading_CancellationTokenSource__Dispose, System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, System_Text_StringBuilder__AppendString, System_Text_StringBuilder__AppendChar, System_Text_StringBuilder__AppendObject, System_Text_StringBuilder__ctor, System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear, Count // Remember to update the AllWellKnownTypeMembers tests when making changes here } }
1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/WellKnownMembers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class WellKnownMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static WellKnownMembers() { byte[] initializationBytes = new byte[] { // System_Math__RoundDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__PowDoubleDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Array__get_Length (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Array__Empty (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Convert__ToBooleanDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToBooleanInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Convert__ToBooleanUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Convert__ToBooleanInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Convert__ToBooleanUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Convert__ToBooleanSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToBooleanDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToSByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToSingleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToDoubleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_CLSCompliantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_CLSCompliantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_FlagsAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_FlagsAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Guid__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Guid, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Type__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Type__GetTypeFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Type__Missing (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Field Signature // System_Type__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Reflection_AssemblyKeyFileAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyFileAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_AssemblyKeyNameAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyNameAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_MethodBase__GetMethodFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, // System_Reflection_MethodBase__GetMethodFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_MethodInfo__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Reflection_MethodInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Delegate__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, // System_Delegate__CreateDelegate4 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Reflection_FieldInfo__GetFieldFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Reflection_FieldInfo__GetFieldFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_Missing__Value (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_Missing, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_Missing, // Field Signature // System_IEquatable_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_IEquatable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IEqualityComparer_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__get_Default (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T,// Return Type // System_AttributeUsageAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, 0, // System_AttributeUsageAttribute__AllowMultiple (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_AttributeUsageAttribute__Inherited (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_ParamArrayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ParamArrayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_STAThreadAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_STAThreadAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Reflection_DefaultMemberAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_DefaultMemberAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_Debugger__Break (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_Debugger, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerDisplayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_DebuggerDisplayAttribute__Type (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerHiddenAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableState, // System_Diagnostics_DebuggerStepThroughAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Runtime_InteropServices_UnknownWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnknownWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_DispatchWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispatchWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, // System_Runtime_InteropServices_CoClassAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_CoClassAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComAwareEventInfo__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComVisibleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DispIdAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispIdAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_GuidAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_GuidAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ComInterfaceType, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_Marshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_BestFitMappingAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_LCIDConversionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_CallingConvention, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Func_T2, 2, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ExtensionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_FixedBufferAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_DynamicAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_CallSite_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, // System_Runtime_CompilerServices_CallSite_T__Target (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices__GetSubArray_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_UnverifiableCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_UnverifiableCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_Permissions_SecurityAction__RequestMinimum (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Security_Permissions_SecurityAction, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // Field Signature // System_Security_Permissions_SecurityPermissionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Activator__CreateInstance (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Activator__CreateInstance_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Threading_Interlocked__CompareExchange (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Interlocked__CompareExchange_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Threading_Monitor__Enter (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Monitor__Enter2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Threading_Monitor__Exit (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Thread__CurrentThread (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Thread, // Return Type // System_Threading_Thread__ManagedThreadId (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Convert (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__GetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Invoke (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__SetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State (byte)MemberFlags.Field, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Field Signature // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Embedded__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_Embedded, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Interaction__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Interaction, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_Strings__AscCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__AscWCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscWStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__ChrInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_Strings__ChrWInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Xml_Linq_XElement__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XElement__ctor2 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XNamespace__Get (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Xml_Linq_XNamespace, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XNamespace, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Windows_Forms_Application__RunForm (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Windows_Forms_Application, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Windows_Forms_Form, // System_Environment__CurrentManagedThreadId (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Environment, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ComponentModel_EditorBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ComponentModel_EditorBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_ComponentModel_EditorBrowsableState, // System_Runtime_GCLatencyMode__SustainedLowLatency (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_GCLatencyMode, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_GCLatencyMode, // Field Signature // System_ValueTuple_T1__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T3__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T4__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T4__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T5__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T5__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T5__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T6__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T6__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T6__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T6__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T7__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T7__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T7__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T7__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T7__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_TRest__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_TRest__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_TRest__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_TRest__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_TRest__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_TRest__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Rest (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 7, // Field Signature // System_ValueTuple_T1__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_ValueTuple_T2__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, // System_ValueTuple_T3__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, // System_ValueTuple_T4__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, // System_ValueTuple_T_T2_T3_T4_T5__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, // System_ValueTuple_T6__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, // System_ValueTuple_T7__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, // System_ValueTuple_TRest__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, (byte)SignatureTypeCode.GenericTypeParameter, 7, // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_TupleElementNamesAttribute // DeclaringTypeId - WellKnownType.ExtSentinel), 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Format_IFormatProvider (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_IFormatProvider, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_NullableAttribute__ctorByte (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableContextAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ReferenceAssemblyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_ObsoleteAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ObsoleteAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Span__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ReadOnlySpan__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Conversion__FixSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__FixDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // Microsoft_VisualBasic_Conversion__IntSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__IntDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // System_Math__CeilingDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__FloorDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__TruncateDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Index__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Index__GetOffset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Range__ctor (byte)(MemberFlags.Constructor), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__StartAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__EndAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_All (byte)(MemberFlags.PropertyGet | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Range__get_Start (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_End (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_IAsyncDisposable__DisposeAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_IAsyncDisposable - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // Return Type: ValueTask // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: IAsyncEnumerator<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, // Argument: CancellationToken (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: ValueTask<bool> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_Generic_IAsyncEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_IValueTaskSource__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_ValueTask_T__ctorSourceAndToken (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: IValueTaskSource<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Threading_Tasks_ValueTask_T__ctorValue (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_ValueTask__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // Argument: IValueTaskSource (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_ITuple__get_Item (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ITuple__get_Length (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_InvalidOperationException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_InvalidOperationException - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_CancellationToken__Equals (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__CreateLinkedTokenSource (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__Token (byte)MemberFlags.Property, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Return Type // System_Threading_CancellationTokenSource__Dispose (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Text_StringBuilder__AppendString (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Text_StringBuilder__AppendChar (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Text_StringBuilder__AppendObject (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Text_StringBuilder__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type }; string[] allNames = new string[(int)WellKnownMember.Count] { "Round", // System_Math__RoundDouble "Pow", // System_Math__PowDoubleDouble "get_Length", // System_Array__get_Length "Empty", // System_Array__Empty "ToBoolean", // System_Convert__ToBooleanDecimal "ToBoolean", // System_Convert__ToBooleanInt32 "ToBoolean", // System_Convert__ToBooleanUInt32 "ToBoolean", // System_Convert__ToBooleanInt64 "ToBoolean", // System_Convert__ToBooleanUInt64 "ToBoolean", // System_Convert__ToBooleanSingle "ToBoolean", // System_Convert__ToBooleanDouble "ToSByte", // System_Convert__ToSByteDecimal "ToSByte", // System_Convert__ToSByteDouble "ToSByte", // System_Convert__ToSByteSingle "ToByte", // System_Convert__ToByteDecimal "ToByte", // System_Convert__ToByteDouble "ToByte", // System_Convert__ToByteSingle "ToInt16", // System_Convert__ToInt16Decimal "ToInt16", // System_Convert__ToInt16Double "ToInt16", // System_Convert__ToInt16Single "ToUInt16", // System_Convert__ToUInt16Decimal "ToUInt16", // System_Convert__ToUInt16Double "ToUInt16", // System_Convert__ToUInt16Single "ToInt32", // System_Convert__ToInt32Decimal "ToInt32", // System_Convert__ToInt32Double "ToInt32", // System_Convert__ToInt32Single "ToUInt32", // System_Convert__ToUInt32Decimal "ToUInt32", // System_Convert__ToUInt32Double "ToUInt32", // System_Convert__ToUInt32Single "ToInt64", // System_Convert__ToInt64Decimal "ToInt64", // System_Convert__ToInt64Double "ToInt64", // System_Convert__ToInt64Single "ToUInt64", // System_Convert__ToUInt64Decimal "ToUInt64", // System_Convert__ToUInt64Double "ToUInt64", // System_Convert__ToUInt64Single "ToSingle", // System_Convert__ToSingleDecimal "ToDouble", // System_Convert__ToDoubleDecimal ".ctor", // System_CLSCompliantAttribute__ctor ".ctor", // System_FlagsAttribute__ctor ".ctor", // System_Guid__ctor "GetTypeFromCLSID", // System_Type__GetTypeFromCLSID "GetTypeFromHandle", // System_Type__GetTypeFromHandle "Missing", // System_Type__Missing WellKnownMemberNames.EqualityOperatorName, // System_Type__op_Equality ".ctor", // System_Reflection_AssemblyKeyFileAttribute__ctor ".ctor", // System_Reflection_AssemblyKeyNameAttribute__ctor "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle2 "CreateDelegate", // System_Reflection_MethodInfo__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate4 "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle2 "Value", // System_Reflection_Missing__Value "Equals", // System_IEquatable_T__Equals "Equals", // System_Collections_Generic_IEqualityComparer_T__Equals "Equals", // System_Collections_Generic_EqualityComparer_T__Equals "GetHashCode", // System_Collections_Generic_EqualityComparer_T__GetHashCode "get_Default", // System_Collections_Generic_EqualityComparer_T__get_Default ".ctor", // System_AttributeUsageAttribute__ctor "AllowMultiple", // System_AttributeUsageAttribute__AllowMultiple "Inherited", // System_AttributeUsageAttribute__Inherited ".ctor", // System_ParamArrayAttribute__ctor ".ctor", // System_STAThreadAttribute__ctor ".ctor", // System_Reflection_DefaultMemberAttribute__ctor "Break", // System_Diagnostics_Debugger__Break ".ctor", // System_Diagnostics_DebuggerDisplayAttribute__ctor "Type", // System_Diagnostics_DebuggerDisplayAttribute__Type ".ctor", // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor ".ctor", // System_Diagnostics_DebuggerHiddenAttribute__ctor ".ctor", // System_Diagnostics_DebuggerBrowsableAttribute__ctor ".ctor", // System_Diagnostics_DebuggerStepThroughAttribute__ctor ".ctor", // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes "Default", // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default "DisableOptimizations", // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations "EnableEditAndContinue", // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue "IgnoreSymbolStoreSequencePoints", // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints ".ctor", // System_Runtime_InteropServices_UnknownWrapper__ctor ".ctor", // System_Runtime_InteropServices_DispatchWrapper__ctor ".ctor", // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType ".ctor", // System_Runtime_InteropServices_CoClassAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComAwareEventInfo__ctor "AddEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler "RemoveEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler ".ctor", // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString ".ctor", // System_Runtime_InteropServices_ComVisibleAttribute__ctor ".ctor", // System_Runtime_InteropServices_DispIdAttribute__ctor ".ctor", // System_Runtime_InteropServices_GuidAttribute__ctor ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 "GetTypeFromCLSID", // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString ".ctor", // System_Runtime_InteropServices_BestFitMappingAttribute__ctor ".ctor", // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor ".ctor", // System_Runtime_InteropServices_LCIDConversionAttribute__ctor ".ctor", // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler "GetOrCreateEventRegistrationTokenTable", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable "InvocationList", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T "RemoveAllEventHandlers", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T ".ctor", // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 ".ctor", // System_Runtime_CompilerServices_ExtensionAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor ".ctor", // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 ".ctor", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor "WrapNonExceptionThrows", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows ".ctor", // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_FixedBufferAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags "Create", // System_Runtime_CompilerServices_CallSite_T__Create "Target", // System_Runtime_CompilerServices_CallSite_T__Target "GetObjectValue", // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject "InitializeArray", // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle "get_OffsetToStringData", // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData "GetSubArray", // System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T "Capture", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture "Throw", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw ".ctor", // System_Security_UnverifiableCodeAttribute__ctor "RequestMinimum", // System_Security_Permissions_SecurityAction__RequestMinimum ".ctor", // System_Security_Permissions_SecurityPermissionAttribute__ctor "SkipVerification", // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification "CreateInstance", // System_Activator__CreateInstance "CreateInstance", // System_Activator__CreateInstance_T "CompareExchange", // System_Threading_Interlocked__CompareExchange "CompareExchange", // System_Threading_Interlocked__CompareExchange_T "Enter", // System_Threading_Monitor__Enter "Enter", // System_Threading_Monitor__Enter2 "Exit", // System_Threading_Monitor__Exit "CurrentThread", // System_Threading_Thread__CurrentThread "ManagedThreadId", // System_Threading_Thread__ManagedThreadId "BinaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation "Convert", // Microsoft_CSharp_RuntimeBinder_Binder__Convert "GetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex "GetMember", // Microsoft_CSharp_RuntimeBinder_Binder__GetMember "Invoke", // Microsoft_CSharp_RuntimeBinder_Binder__Invoke "InvokeConstructor", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor "InvokeMember", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember "IsEvent", // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent "SetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex "SetMember", // Microsoft_CSharp_RuntimeBinder_Binder__SetMember "UnaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation "Create", // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject "ToGenericParameter", // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object "ChangeType", // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType "PlusObject", // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject "NegateObject", // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject "NotObject", // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject "AndObject", // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject "OrObject", // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject "XorObject", // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject "AddObject", // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject "SubtractObject", // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject "MultiplyObject", // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject "DivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject "ExponentObject", // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject "ModObject", // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject "IntDivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject "LeftShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject "RightShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject "ConcatenateObject", // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject "CompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean "CompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean "CompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean "CompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean "CompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean "CompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean "ConditionalCompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean "ConditionalCompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean "ConditionalCompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean "ConditionalCompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean "ConditionalCompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean "ConditionalCompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean "LateCall", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall "LateGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet "LateSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet "LateSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex "LateIndexGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet "LateIndexSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet "LateIndexSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex ".ctor", // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor ".ctor", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor "State", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State "MidStmtStr", // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr ".ctor", // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor ".ctor", // Microsoft_VisualBasic_Embedded__ctor "CopyArray", // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray "LikeString", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod "LikeObject", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod "CreateProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 "ClearProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError "EndApp", // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp "ForLoopInitObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj "ForNextCheckObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj "CheckForSyncLockOnValueType", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType "CallByName", // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName "IsNumeric", // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName "TypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName "VbTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName "IsNumeric", // Microsoft_VisualBasic_Information__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_Information__SystemTypeName "TypeName", // Microsoft_VisualBasic_Information__TypeName "VbTypeName", // Microsoft_VisualBasic_Information__VbTypeName "CallByName", // Microsoft_VisualBasic_Interaction__CallByName "MoveNext", // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext "SetStateMachine", // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task ".ctor", // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor "Asc", // Microsoft_VisualBasic_Strings__AscCharInt32 "Asc", // Microsoft_VisualBasic_Strings__AscStringInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWCharInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWStringInt32 "Chr", // Microsoft_VisualBasic_Strings__ChrInt32Char "ChrW", // Microsoft_VisualBasic_Strings__ChrWInt32Char ".ctor", // System_Xml_Linq_XElement__ctor ".ctor", // System_Xml_Linq_XElement__ctor2 "Get", // System_Xml_Linq_XNamespace__Get "Run", // System_Windows_Forms_Application__RunForm "CurrentManagedThreadId", // System_Environment__CurrentManagedThreadId ".ctor", // System_ComponentModel_EditorBrowsableAttribute__ctor "SustainedLowLatency", // System_Runtime_GCLatencyMode__SustainedLowLatency "Item1", // System_ValueTuple_T1__Item1 "Item1", // System_ValueTuple_T2__Item1 "Item2", // System_ValueTuple_T2__Item2 "Item1", // System_ValueTuple_T3__Item1 "Item2", // System_ValueTuple_T3__Item2 "Item3", // System_ValueTuple_T3__Item3 "Item1", // System_ValueTuple_T4__Item1 "Item2", // System_ValueTuple_T4__Item2 "Item3", // System_ValueTuple_T4__Item3 "Item4", // System_ValueTuple_T4__Item4 "Item1", // System_ValueTuple_T5__Item1 "Item2", // System_ValueTuple_T5__Item2 "Item3", // System_ValueTuple_T5__Item3 "Item4", // System_ValueTuple_T5__Item4 "Item5", // System_ValueTuple_T5__Item5 "Item1", // System_ValueTuple_T6__Item1 "Item2", // System_ValueTuple_T6__Item2 "Item3", // System_ValueTuple_T6__Item3 "Item4", // System_ValueTuple_T6__Item4 "Item5", // System_ValueTuple_T6__Item5 "Item6", // System_ValueTuple_T6__Item6 "Item1", // System_ValueTuple_T7__Item1 "Item2", // System_ValueTuple_T7__Item2 "Item3", // System_ValueTuple_T7__Item3 "Item4", // System_ValueTuple_T7__Item4 "Item5", // System_ValueTuple_T7__Item5 "Item6", // System_ValueTuple_T7__Item6 "Item7", // System_ValueTuple_T7__Item7 "Item1", // System_ValueTuple_TRest__Item1 "Item2", // System_ValueTuple_TRest__Item2 "Item3", // System_ValueTuple_TRest__Item3 "Item4", // System_ValueTuple_TRest__Item4 "Item5", // System_ValueTuple_TRest__Item5 "Item6", // System_ValueTuple_TRest__Item6 "Item7", // System_ValueTuple_TRest__Item7 "Rest", // System_ValueTuple_TRest__Rest ".ctor", // System_ValueTuple_T1__ctor ".ctor", // System_ValueTuple_T2__ctor ".ctor", // System_ValueTuple_T3__ctor ".ctor", // System_ValueTuple_T4__ctor ".ctor", // System_ValueTuple_T5__ctor ".ctor", // System_ValueTuple_T6__ctor ".ctor", // System_ValueTuple_T7__ctor ".ctor", // System_ValueTuple_TRest__ctor ".ctor", // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames "Format", // System_String__Format_IFormatProvider "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorByte ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags ".ctor", // System_Runtime_CompilerServices_NullableContextAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ObsoleteAttribute__ctor ".ctor", // System_Span__ctor "get_Item", // System_Span__get_Item "get_Length", // System_Span__get_Length ".ctor", // System_ReadOnlySpan__ctor "get_Item", // System_ReadOnlySpan__get_Item "get_Length", // System_ReadOnlySpan__get_Length ".ctor", // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor "Fix", // Microsoft_VisualBasic_Conversion__FixSingle "Fix", // Microsoft_VisualBasic_Conversion__FixDouble "Int", // Microsoft_VisualBasic_Conversion__IntSingle "Int", // Microsoft_VisualBasic_Conversion__IntDouble "Ceiling", // System_Math__CeilingDouble "Floor", // System_Math__FloorDouble "Truncate", // System_Math__TruncateDouble ".ctor", // System_Index__ctor "GetOffset", // System_Index__GetOffset ".ctor", // System_Range__ctor "StartAt", // System_Range__StartAt "EndAt", // System_Range__StartAt "get_All", // System_Range__get_All "get_Start", // System_Range__get_Start "get_End", // System_Range__get_End ".ctor", // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor "DisposeAsync", // System_IAsyncDisposable__DisposeAsync "GetAsyncEnumerator", // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator "MoveNextAsync", // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync "get_Current", // System_Collections_Generic_IAsyncEnumerator_T__get_Current "GetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted "Reset", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset "SetException", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException "SetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult "get_Version", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted ".ctor", // System_Threading_Tasks_ValueTask_T__ctor ".ctor", // System_Threading_Tasks_ValueTask_T__ctorValue ".ctor", // System_Threading_Tasks_ValueTask__ctor "Create", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create "Complete", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted "MoveNext", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T "get_Item", // System_Runtime_CompilerServices_ITuple__get_Item "get_Length", // System_Runtime_CompilerServices_ITuple__get_Length ".ctor", // System_InvalidOperationException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject "Equals", // System_Threading_CancellationToken__Equals "CreateLinkedTokenSource", // System_Threading_CancellationTokenSource__CreateLinkedTokenSource "Token", // System_Threading_CancellationTokenSource__Token "Dispose", // System_Threading_CancellationTokenSource__Dispose ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags "Append", // System_Text_StringBuilder__AppendString "Append", // System_Text_StringBuilder__AppendChar "Append", // System_Text_StringBuilder__AppendObject ".ctor", // System_Text_StringBuilder__ctor "ToStringAndClear", // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(WellKnownMember member) { return s_descriptors[(int)member]; } /// <summary> /// This function defines whether an attribute is optional or not. /// </summary> /// <param name="attributeMember">The attribute member.</param> internal static bool IsSynthesizedAttributeOptional(WellKnownMember attributeMember) { switch (attributeMember) { case WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes: case WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor: case WellKnownMember.System_STAThreadAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: return true; default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class WellKnownMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static WellKnownMembers() { byte[] initializationBytes = new byte[] { // System_Math__RoundDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__PowDoubleDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Array__get_Length (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Array__Empty (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Array, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Convert__ToBooleanDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToBooleanInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Convert__ToBooleanUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Convert__ToBooleanInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Convert__ToBooleanUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Convert__ToBooleanSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToBooleanDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToSByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToSByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToByteDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToByteDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToByteSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt16Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt16Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt16Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt32Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt32Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt32Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToUInt64Decimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToUInt64Double (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Convert__ToUInt64Single (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Convert__ToSingleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Convert__ToDoubleDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Convert, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_CLSCompliantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_CLSCompliantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_FlagsAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_FlagsAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Guid__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Guid, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Type__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Type__GetTypeFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Type__Missing (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Field Signature // System_Type__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Type, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Reflection_AssemblyKeyFileAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyFileAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_AssemblyKeyNameAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_AssemblyKeyNameAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Reflection_MethodBase__GetMethodFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, // System_Reflection_MethodBase__GetMethodFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_MethodBase, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodBase, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeMethodHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_MethodInfo__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Reflection_MethodInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Delegate__CreateDelegate (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, // System_Delegate__CreateDelegate4 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_MethodInfo, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Reflection_FieldInfo__GetFieldFromHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Reflection_FieldInfo__GetFieldFromHandle2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_FieldInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_FieldInfo, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeTypeHandle, // System_Reflection_Missing__Value (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Reflection_Missing, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Reflection_Missing, // Field Signature // System_IEquatable_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_IEquatable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IEqualityComparer_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_EqualityComparer_T__get_Default (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Collections_Generic_EqualityComparer_T,// Return Type // System_AttributeUsageAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, 0, // System_AttributeUsageAttribute__AllowMultiple (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_AttributeUsageAttribute__Inherited (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_AttributeUsageAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_ParamArrayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ParamArrayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_STAThreadAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_STAThreadAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Reflection_DefaultMemberAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Reflection_DefaultMemberAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_Debugger__Break (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_Debugger, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerDisplayAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Diagnostics_DebuggerDisplayAttribute__Type (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerDisplayAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerNonUserCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerHiddenAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerHiddenAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggerBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggerBrowsableState, // System_Diagnostics_DebuggerStepThroughAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggerStepThroughAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes, // Field Signature // System_Runtime_InteropServices_UnknownWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnknownWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_DispatchWrapper__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispatchWrapper, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ClassInterfaceType, // System_Runtime_InteropServices_CoClassAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_CoClassAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComAwareEventInfo__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComAwareEventInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComEventInterfaceAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComSourceInterfacesAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_ComVisibleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_ComVisibleAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DispIdAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DispIdAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_GuidAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_GuidAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_ComInterfaceType, // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_InterfaceTypeAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_Marshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_TypeIdentifierAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_InteropServices_BestFitMappingAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_BestFitMappingAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_DefaultParameterValueAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_InteropServices_LCIDConversionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_LCIDConversionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_CallingConvention, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Func_T2, 2, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DateTimeConstantAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DecimalConstantAttribute, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ExtensionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_ExtensionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CompilationRelaxationsAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeCompatibilityAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_UnsafeValueTypeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_FixedBufferAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_FixedBufferAttribute, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_DynamicAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_DynamicAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_CallSite_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, // System_Runtime_CompilerServices_CallSite_T__Target (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_CallSite_T, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_RuntimeFieldHandle, // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData (byte)(MemberFlags.PropertyGet | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices__GetSubArray_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 1, // Arity 2, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices__EnsureSufficientExecutionStack (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_RuntimeHelpers, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_ExceptionServices_ExceptionDispatchInfo, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_UnverifiableCodeAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_UnverifiableCodeAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Security_Permissions_SecurityAction__RequestMinimum (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Security_Permissions_SecurityAction, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // Field Signature // System_Security_Permissions_SecurityPermissionAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Security_Permissions_SecurityAction, // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Security_Permissions_SecurityPermissionAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type // System_Activator__CreateInstance (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Activator__CreateInstance_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Activator, // DeclaringTypeId 1, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type // System_Threading_Interlocked__CompareExchange (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Interlocked__CompareExchange_T (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Interlocked, // DeclaringTypeId 1, // Arity 3, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Threading_Monitor__Enter (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Monitor__Enter2 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Threading_Monitor__Exit (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Monitor, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_Thread__CurrentThread (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Thread, // Return Type // System_Threading_Thread__ManagedThreadId (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Threading_Thread, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Convert (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__GetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__Invoke (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__SetMember (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_Binder, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_CallSiteBinder, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpBinderFlags, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Linq_Expressions_ExpressionType, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerable_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfoFlags, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericMethodParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Conversions, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State (byte)MemberFlags.Field, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Field Signature // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_IncompleteInitialization, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Embedded__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.Microsoft_VisualBasic_Embedded, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Utils, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Array, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CompareMethod, // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ProjectData, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__IsNumeric (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__SystemTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Information__TypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_VisualBasic_Information__VbTypeName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Information, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Interaction__CallByName (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Interaction, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.Microsoft_VisualBasic_CallType, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncVoidMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task, // Return Type // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine (byte)MemberFlags.Method, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine, // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task (byte)MemberFlags.Property, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Threading_Tasks_Task_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_AsyncStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Runtime_CompilerServices_IteratorStateMachineAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // Microsoft_VisualBasic_Strings__AscCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__AscWCharInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Microsoft_VisualBasic_Strings__AscWStringInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Microsoft_VisualBasic_Strings__ChrInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_VisualBasic_Strings__ChrWInt32Char (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.Microsoft_VisualBasic_Strings, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Xml_Linq_XElement__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XElement__ctor2 (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_Xml_Linq_XElement, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XName, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Xml_Linq_XNamespace__Get (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Xml_Linq_XNamespace, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Xml_Linq_XNamespace, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Windows_Forms_Application__RunForm (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Windows_Forms_Application, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Windows_Forms_Form, // System_Environment__CurrentManagedThreadId (byte)(MemberFlags.Property | MemberFlags.Static), // Flags (byte)WellKnownType.System_Environment, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ComponentModel_EditorBrowsableAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ComponentModel_EditorBrowsableAttribute, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_ComponentModel_EditorBrowsableState, // System_Runtime_GCLatencyMode__SustainedLowLatency (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)WellKnownType.System_Runtime_GCLatencyMode, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Runtime_GCLatencyMode, // Field Signature // System_ValueTuple_T1__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T2__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T3__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T3__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T4__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T4__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T4__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T5__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T5__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T5__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T5__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T6__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T6__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T6__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T6__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T6__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_T7__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_T7__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_T7__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_T7__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_T7__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_T7__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Item1 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 0, // Field Signature // System_ValueTuple_TRest__Item2 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 1, // Field Signature // System_ValueTuple_TRest__Item3 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 2, // Field Signature // System_ValueTuple_TRest__Item4 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 3, // Field Signature // System_ValueTuple_TRest__Item5 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 4, // Field Signature // System_ValueTuple_TRest__Item6 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 5, // Field Signature // System_ValueTuple_TRest__Item7 (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 6, // Field Signature // System_ValueTuple_TRest__Rest (byte)MemberFlags.Field, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.GenericTypeParameter, 7, // Field Signature // System_ValueTuple_T1__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T1, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_ValueTuple_T2__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T2, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, // System_ValueTuple_T3__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.System_ValueTuple_T3, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, // System_ValueTuple_T4__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T4 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, // System_ValueTuple_T_T2_T3_T4_T5__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T5 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, // System_ValueTuple_T6__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T6 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 6, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, // System_ValueTuple_T7__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_T7 - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 7, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, // System_ValueTuple_TRest__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ValueTuple_TRest - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 8, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.GenericTypeParameter, 1, (byte)SignatureTypeCode.GenericTypeParameter, 2, (byte)SignatureTypeCode.GenericTypeParameter, 3, (byte)SignatureTypeCode.GenericTypeParameter, 4, (byte)SignatureTypeCode.GenericTypeParameter, 5, (byte)SignatureTypeCode.GenericTypeParameter, 6, (byte)SignatureTypeCode.GenericTypeParameter, 7, // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_TupleElementNamesAttribute // DeclaringTypeId - WellKnownType.ExtSentinel), 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Format_IFormatProvider (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_IFormatProvider, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Guid, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_NullableAttribute__ctorByte (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullableContextAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ReferenceAssemblyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_ObsoleteAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ObsoleteAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Span__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Span__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Span_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_ReadOnlySpan__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Item (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_ReadOnlySpan__get_Length (byte)(MemberFlags.PropertyGet), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_ReadOnlySpan_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // Microsoft_VisualBasic_Conversion__FixSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__FixDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // Microsoft_VisualBasic_Conversion__IntSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // Number As System.Single // Microsoft_VisualBasic_Conversion__IntDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.Microsoft_VisualBasic_Conversion - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Number As System.Double // System_Math__CeilingDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__FloorDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Math__TruncateDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.System_Math, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Index__ctor (byte)(MemberFlags.Constructor), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Index__GetOffset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Range__ctor (byte)(MemberFlags.Constructor), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__StartAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__EndAt (byte)(MemberFlags.Method | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_All (byte)(MemberFlags.PropertyGet | MemberFlags.Static), (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // System_Range__get_Start (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Range__get_End (byte)MemberFlags.PropertyGet, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Range - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Index - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Type, // System_IAsyncDisposable__DisposeAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_IAsyncDisposable - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // Return Type: ValueTask // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: IAsyncEnumerator<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, // Argument: CancellationToken (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, // Return Type: ValueTask<bool> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_Generic_IAsyncEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Exception, // Argument // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, (byte)MemberFlags.PropertyGet, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // Return Type: T (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_Sources_IValueTaskSource__GetResult, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument: short // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: Action<object> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.System_Action_T, 1, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags - WellKnownType.ExtSentinel), // Argument // System_Threading_Tasks_ValueTask_T__ctorSourceAndToken (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeInstance, // Argument: IValueTaskSource<T> (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T - WellKnownType.ExtSentinel), 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Threading_Tasks_ValueTask_T__ctorValue (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask_T - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.GenericTypeParameter, 0, // Argument: T // System_Threading_Tasks_ValueTask__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_ValueTask - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource - WellKnownType.ExtSentinel), // Argument: IValueTaskSource (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // Argument // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 2, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, (byte)SpecialType.System_Object, // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 1, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.ByReference, (byte)SignatureTypeCode.GenericMethodParameter, 0, // System_Runtime_CompilerServices_ITuple__get_Item (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Runtime_CompilerServices_ITuple__get_Length (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_ITuple - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // Return Type // System_InvalidOperationException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_InvalidOperationException - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException - WellKnownType.ExtSentinel),// DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Threading_CancellationToken__Equals (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__CreateLinkedTokenSource (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken // System_Threading_CancellationTokenSource__Token (byte)MemberFlags.Property, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Return Type // System_Threading_CancellationTokenSource__Dispose (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationTokenSource - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Text_StringBuilder__AppendString (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Text_StringBuilder__AppendChar (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Text_StringBuilder__AppendObject (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Text_StringBuilder__ctor (byte)MemberFlags.Constructor, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Text_StringBuilder - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear (byte)MemberFlags.Method, // Flags (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler - WellKnownType.ExtSentinel), // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type }; string[] allNames = new string[(int)WellKnownMember.Count] { "Round", // System_Math__RoundDouble "Pow", // System_Math__PowDoubleDouble "get_Length", // System_Array__get_Length "Empty", // System_Array__Empty "ToBoolean", // System_Convert__ToBooleanDecimal "ToBoolean", // System_Convert__ToBooleanInt32 "ToBoolean", // System_Convert__ToBooleanUInt32 "ToBoolean", // System_Convert__ToBooleanInt64 "ToBoolean", // System_Convert__ToBooleanUInt64 "ToBoolean", // System_Convert__ToBooleanSingle "ToBoolean", // System_Convert__ToBooleanDouble "ToSByte", // System_Convert__ToSByteDecimal "ToSByte", // System_Convert__ToSByteDouble "ToSByte", // System_Convert__ToSByteSingle "ToByte", // System_Convert__ToByteDecimal "ToByte", // System_Convert__ToByteDouble "ToByte", // System_Convert__ToByteSingle "ToInt16", // System_Convert__ToInt16Decimal "ToInt16", // System_Convert__ToInt16Double "ToInt16", // System_Convert__ToInt16Single "ToUInt16", // System_Convert__ToUInt16Decimal "ToUInt16", // System_Convert__ToUInt16Double "ToUInt16", // System_Convert__ToUInt16Single "ToInt32", // System_Convert__ToInt32Decimal "ToInt32", // System_Convert__ToInt32Double "ToInt32", // System_Convert__ToInt32Single "ToUInt32", // System_Convert__ToUInt32Decimal "ToUInt32", // System_Convert__ToUInt32Double "ToUInt32", // System_Convert__ToUInt32Single "ToInt64", // System_Convert__ToInt64Decimal "ToInt64", // System_Convert__ToInt64Double "ToInt64", // System_Convert__ToInt64Single "ToUInt64", // System_Convert__ToUInt64Decimal "ToUInt64", // System_Convert__ToUInt64Double "ToUInt64", // System_Convert__ToUInt64Single "ToSingle", // System_Convert__ToSingleDecimal "ToDouble", // System_Convert__ToDoubleDecimal ".ctor", // System_CLSCompliantAttribute__ctor ".ctor", // System_FlagsAttribute__ctor ".ctor", // System_Guid__ctor "GetTypeFromCLSID", // System_Type__GetTypeFromCLSID "GetTypeFromHandle", // System_Type__GetTypeFromHandle "Missing", // System_Type__Missing WellKnownMemberNames.EqualityOperatorName, // System_Type__op_Equality ".ctor", // System_Reflection_AssemblyKeyFileAttribute__ctor ".ctor", // System_Reflection_AssemblyKeyNameAttribute__ctor "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle "GetMethodFromHandle", // System_Reflection_MethodBase__GetMethodFromHandle2 "CreateDelegate", // System_Reflection_MethodInfo__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate "CreateDelegate", // System_Delegate__CreateDelegate4 "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle "GetFieldFromHandle", // System_Reflection_FieldInfo__GetFieldFromHandle2 "Value", // System_Reflection_Missing__Value "Equals", // System_IEquatable_T__Equals "Equals", // System_Collections_Generic_IEqualityComparer_T__Equals "Equals", // System_Collections_Generic_EqualityComparer_T__Equals "GetHashCode", // System_Collections_Generic_EqualityComparer_T__GetHashCode "get_Default", // System_Collections_Generic_EqualityComparer_T__get_Default ".ctor", // System_AttributeUsageAttribute__ctor "AllowMultiple", // System_AttributeUsageAttribute__AllowMultiple "Inherited", // System_AttributeUsageAttribute__Inherited ".ctor", // System_ParamArrayAttribute__ctor ".ctor", // System_STAThreadAttribute__ctor ".ctor", // System_Reflection_DefaultMemberAttribute__ctor "Break", // System_Diagnostics_Debugger__Break ".ctor", // System_Diagnostics_DebuggerDisplayAttribute__ctor "Type", // System_Diagnostics_DebuggerDisplayAttribute__Type ".ctor", // System_Diagnostics_DebuggerNonUserCodeAttribute__ctor ".ctor", // System_Diagnostics_DebuggerHiddenAttribute__ctor ".ctor", // System_Diagnostics_DebuggerBrowsableAttribute__ctor ".ctor", // System_Diagnostics_DebuggerStepThroughAttribute__ctor ".ctor", // System_Diagnostics_DebuggableAttribute__ctorDebuggingModes "Default", // System_Diagnostics_DebuggableAttribute_DebuggingModes__Default "DisableOptimizations", // System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations "EnableEditAndContinue", // System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue "IgnoreSymbolStoreSequencePoints", // System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints ".ctor", // System_Runtime_InteropServices_UnknownWrapper__ctor ".ctor", // System_Runtime_InteropServices_DispatchWrapper__ctor ".ctor", // System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType ".ctor", // System_Runtime_InteropServices_CoClassAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComAwareEventInfo__ctor "AddEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__AddEventHandler "RemoveEventHandler", // System_Runtime_InteropServices_ComAwareEventInfo__RemoveEventHandler ".ctor", // System_Runtime_InteropServices_ComEventInterfaceAttribute__ctor ".ctor", // System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString ".ctor", // System_Runtime_InteropServices_ComVisibleAttribute__ctor ".ctor", // System_Runtime_InteropServices_DispIdAttribute__ctor ".ctor", // System_Runtime_InteropServices_GuidAttribute__ctor ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorComInterfaceType ".ctor", // System_Runtime_InteropServices_InterfaceTypeAttribute__ctorInt16 "GetTypeFromCLSID", // System_Runtime_InteropServices_Marshal__GetTypeFromCLSID ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctor ".ctor", // System_Runtime_InteropServices_TypeIdentifierAttribute__ctorStringString ".ctor", // System_Runtime_InteropServices_BestFitMappingAttribute__ctor ".ctor", // System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor ".ctor", // System_Runtime_InteropServices_LCIDConversionAttribute__ctor ".ctor", // System_Runtime_InteropServices_UnmanagedFunctionPointerAttribute__ctor "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler "GetOrCreateEventRegistrationTokenTable", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable "InvocationList", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler "AddEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__AddEventHandler_T "RemoveAllEventHandlers", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveAllEventHandlers "RemoveEventHandler", // System_Runtime_InteropServices_WindowsRuntime_WindowsRuntimeMarshal__RemoveEventHandler_T ".ctor", // System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32 ".ctor", // System_Runtime_CompilerServices_ExtensionAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor ".ctor", // System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_CompilationRelaxationsAttribute__ctorInt32 ".ctor", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__ctor "WrapNonExceptionThrows", // System_Runtime_CompilerServices_RuntimeCompatibilityAttribute__WrapNonExceptionThrows ".ctor", // System_Runtime_CompilerServices_UnsafeValueTypeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_FixedBufferAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctor ".ctor", // System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags "Create", // System_Runtime_CompilerServices_CallSite_T__Create "Target", // System_Runtime_CompilerServices_CallSite_T__Target "GetObjectValue", // System_Runtime_CompilerServices_RuntimeHelpers__GetObjectValueObject "InitializeArray", // System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle "get_OffsetToStringData", // System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData "GetSubArray", // System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T "EnsureSufficientExecutionStack", // System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack "Capture", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Capture "Throw", // System_Runtime_ExceptionServices_ExceptionDispatchInfo__Throw ".ctor", // System_Security_UnverifiableCodeAttribute__ctor "RequestMinimum", // System_Security_Permissions_SecurityAction__RequestMinimum ".ctor", // System_Security_Permissions_SecurityPermissionAttribute__ctor "SkipVerification", // System_Security_Permissions_SecurityPermissionAttribute__SkipVerification "CreateInstance", // System_Activator__CreateInstance "CreateInstance", // System_Activator__CreateInstance_T "CompareExchange", // System_Threading_Interlocked__CompareExchange "CompareExchange", // System_Threading_Interlocked__CompareExchange_T "Enter", // System_Threading_Monitor__Enter "Enter", // System_Threading_Monitor__Enter2 "Exit", // System_Threading_Monitor__Exit "CurrentThread", // System_Threading_Thread__CurrentThread "ManagedThreadId", // System_Threading_Thread__ManagedThreadId "BinaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation "Convert", // Microsoft_CSharp_RuntimeBinder_Binder__Convert "GetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__GetIndex "GetMember", // Microsoft_CSharp_RuntimeBinder_Binder__GetMember "Invoke", // Microsoft_CSharp_RuntimeBinder_Binder__Invoke "InvokeConstructor", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor "InvokeMember", // Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember "IsEvent", // Microsoft_CSharp_RuntimeBinder_Binder__IsEvent "SetIndex", // Microsoft_CSharp_RuntimeBinder_Binder__SetIndex "SetMember", // Microsoft_CSharp_RuntimeBinder_Binder__SetMember "UnaryOperation", // Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation "Create", // Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar "ToString", // Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject "ToBoolean", // Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject "ToSByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject "ToByte", // Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject "ToShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject "ToUShort", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject "ToInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject "ToUInteger", // Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject "ToLong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject "ToULong", // Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject "ToSingle", // Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject "ToDouble", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject "ToDecimal", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject "ToDate", // Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject "ToChar", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject "ToCharArrayRankOne", // Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject "ToGenericParameter", // Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object "ChangeType", // Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType "PlusObject", // Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject "NegateObject", // Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject "NotObject", // Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject "AndObject", // Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject "OrObject", // Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject "XorObject", // Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject "AddObject", // Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject "SubtractObject", // Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject "MultiplyObject", // Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject "DivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject "ExponentObject", // Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject "ModObject", // Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject "IntDivideObject", // Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject "LeftShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject "RightShiftObject", // Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject "ConcatenateObject", // Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject "CompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean "CompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean "CompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean "CompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean "CompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean "CompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean "ConditionalCompareObjectEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean "ConditionalCompareObjectNotEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean "ConditionalCompareObjectLess", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean "ConditionalCompareObjectLessEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean "ConditionalCompareObjectGreaterEqual", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean "ConditionalCompareObjectGreater", // Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean "CompareString", // Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean "LateCall", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall "LateGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet "LateSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet "LateSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex "LateIndexGet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet "LateIndexSet", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet "LateIndexSetComplex", // Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex ".ctor", // Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor ".ctor", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__ctor "State", // Microsoft_VisualBasic_CompilerServices_StaticLocalInitFlag__State "MidStmtStr", // Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr ".ctor", // Microsoft_VisualBasic_CompilerServices_IncompleteInitialization__ctor ".ctor", // Microsoft_VisualBasic_Embedded__ctor "CopyArray", // Microsoft_VisualBasic_CompilerServices_Utils__CopyArray "LikeString", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod "LikeObject", // Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod "CreateProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError "SetProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32 "ClearProjectError", // Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError "EndApp", // Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp "ForLoopInitObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj "ForNextCheckObj", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj "CheckForSyncLockOnValueType", // Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType "CallByName", // Microsoft_VisualBasic_CompilerServices_Versioned__CallByName "IsNumeric", // Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName "TypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__TypeName "VbTypeName", // Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName "IsNumeric", // Microsoft_VisualBasic_Information__IsNumeric "SystemTypeName", // Microsoft_VisualBasic_Information__SystemTypeName "TypeName", // Microsoft_VisualBasic_Information__TypeName "VbTypeName", // Microsoft_VisualBasic_Information__VbTypeName "CallByName", // Microsoft_VisualBasic_Interaction__CallByName "MoveNext", // System_Runtime_CompilerServices_IAsyncStateMachine_MoveNext "SetStateMachine", // System_Runtime_CompilerServices_IAsyncStateMachine_SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncVoidMethodBuilder__SetStateMachine "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder__Task "Create", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Create "SetException", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetException "SetResult", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetResult "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__AwaitUnsafeOnCompleted "Start", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Start_T "SetStateMachine", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__SetStateMachine "Task", // System_Runtime_CompilerServices_AsyncTaskMethodBuilder_T__Task ".ctor", // System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor "Asc", // Microsoft_VisualBasic_Strings__AscCharInt32 "Asc", // Microsoft_VisualBasic_Strings__AscStringInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWCharInt32 "AscW", // Microsoft_VisualBasic_Strings__AscWStringInt32 "Chr", // Microsoft_VisualBasic_Strings__ChrInt32Char "ChrW", // Microsoft_VisualBasic_Strings__ChrWInt32Char ".ctor", // System_Xml_Linq_XElement__ctor ".ctor", // System_Xml_Linq_XElement__ctor2 "Get", // System_Xml_Linq_XNamespace__Get "Run", // System_Windows_Forms_Application__RunForm "CurrentManagedThreadId", // System_Environment__CurrentManagedThreadId ".ctor", // System_ComponentModel_EditorBrowsableAttribute__ctor "SustainedLowLatency", // System_Runtime_GCLatencyMode__SustainedLowLatency "Item1", // System_ValueTuple_T1__Item1 "Item1", // System_ValueTuple_T2__Item1 "Item2", // System_ValueTuple_T2__Item2 "Item1", // System_ValueTuple_T3__Item1 "Item2", // System_ValueTuple_T3__Item2 "Item3", // System_ValueTuple_T3__Item3 "Item1", // System_ValueTuple_T4__Item1 "Item2", // System_ValueTuple_T4__Item2 "Item3", // System_ValueTuple_T4__Item3 "Item4", // System_ValueTuple_T4__Item4 "Item1", // System_ValueTuple_T5__Item1 "Item2", // System_ValueTuple_T5__Item2 "Item3", // System_ValueTuple_T5__Item3 "Item4", // System_ValueTuple_T5__Item4 "Item5", // System_ValueTuple_T5__Item5 "Item1", // System_ValueTuple_T6__Item1 "Item2", // System_ValueTuple_T6__Item2 "Item3", // System_ValueTuple_T6__Item3 "Item4", // System_ValueTuple_T6__Item4 "Item5", // System_ValueTuple_T6__Item5 "Item6", // System_ValueTuple_T6__Item6 "Item1", // System_ValueTuple_T7__Item1 "Item2", // System_ValueTuple_T7__Item2 "Item3", // System_ValueTuple_T7__Item3 "Item4", // System_ValueTuple_T7__Item4 "Item5", // System_ValueTuple_T7__Item5 "Item6", // System_ValueTuple_T7__Item6 "Item7", // System_ValueTuple_T7__Item7 "Item1", // System_ValueTuple_TRest__Item1 "Item2", // System_ValueTuple_TRest__Item2 "Item3", // System_ValueTuple_TRest__Item3 "Item4", // System_ValueTuple_TRest__Item4 "Item5", // System_ValueTuple_TRest__Item5 "Item6", // System_ValueTuple_TRest__Item6 "Item7", // System_ValueTuple_TRest__Item7 "Rest", // System_ValueTuple_TRest__Rest ".ctor", // System_ValueTuple_T1__ctor ".ctor", // System_ValueTuple_T2__ctor ".ctor", // System_ValueTuple_T3__ctor ".ctor", // System_ValueTuple_T4__ctor ".ctor", // System_ValueTuple_T5__ctor ".ctor", // System_ValueTuple_T6__ctor ".ctor", // System_ValueTuple_T7__ctor ".ctor", // System_ValueTuple_TRest__ctor ".ctor", // System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames "Format", // System_String__Format_IFormatProvider "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile "CreatePayload", // Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorByte ".ctor", // System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags ".ctor", // System_Runtime_CompilerServices_NullableContextAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor ".ctor", // System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor ".ctor", // System_Runtime_CompilerServices_ObsoleteAttribute__ctor ".ctor", // System_Span__ctor "get_Item", // System_Span__get_Item "get_Length", // System_Span__get_Length ".ctor", // System_ReadOnlySpan__ctor "get_Item", // System_ReadOnlySpan__get_Item "get_Length", // System_ReadOnlySpan__get_Length ".ctor", // System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor "Fix", // Microsoft_VisualBasic_Conversion__FixSingle "Fix", // Microsoft_VisualBasic_Conversion__FixDouble "Int", // Microsoft_VisualBasic_Conversion__IntSingle "Int", // Microsoft_VisualBasic_Conversion__IntDouble "Ceiling", // System_Math__CeilingDouble "Floor", // System_Math__FloorDouble "Truncate", // System_Math__TruncateDouble ".ctor", // System_Index__ctor "GetOffset", // System_Index__GetOffset ".ctor", // System_Range__ctor "StartAt", // System_Range__StartAt "EndAt", // System_Range__StartAt "get_All", // System_Range__get_All "get_Start", // System_Range__get_Start "get_End", // System_Range__get_End ".ctor", // System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor "DisposeAsync", // System_IAsyncDisposable__DisposeAsync "GetAsyncEnumerator", // System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator "MoveNextAsync", // System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync "get_Current", // System_Collections_Generic_IAsyncEnumerator_T__get_Current "GetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted "Reset", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset "SetException", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException "SetResult", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult "get_Version", // System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted "GetResult", // System_Threading_Tasks_Sources_IValueTaskSource__GetResult "GetStatus", // System_Threading_Tasks_Sources_IValueTaskSource__GetStatus "OnCompleted", // System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted ".ctor", // System_Threading_Tasks_ValueTask_T__ctor ".ctor", // System_Threading_Tasks_ValueTask_T__ctorValue ".ctor", // System_Threading_Tasks_ValueTask__ctor "Create", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create "Complete", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete "AwaitOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted "AwaitUnsafeOnCompleted", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted "MoveNext", // System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T "get_Item", // System_Runtime_CompilerServices_ITuple__get_Item "get_Length", // System_Runtime_CompilerServices_ITuple__get_Length ".ctor", // System_InvalidOperationException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject "Equals", // System_Threading_CancellationToken__Equals "CreateLinkedTokenSource", // System_Threading_CancellationTokenSource__CreateLinkedTokenSource "Token", // System_Threading_CancellationTokenSource__Token "Dispose", // System_Threading_CancellationTokenSource__Dispose ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctor ".ctor", // System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags "Append", // System_Text_StringBuilder__AppendString "Append", // System_Text_StringBuilder__AppendChar "Append", // System_Text_StringBuilder__AppendObject ".ctor", // System_Text_StringBuilder__ctor "ToStringAndClear", // System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(WellKnownMember member) { return s_descriptors[(int)member]; } /// <summary> /// This function defines whether an attribute is optional or not. /// </summary> /// <param name="attributeMember">The attribute member.</param> internal static bool IsSynthesizedAttributeOptional(WellKnownMember attributeMember) { switch (attributeMember) { case WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes: case WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerHiddenAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerDisplayAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor: case WellKnownMember.System_Diagnostics_DebuggerNonUserCodeAttribute__ctor: case WellKnownMember.System_STAThreadAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor: case WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor: return true; default: return false; } } } }
1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Test/Core/TempFiles/DisposableDirectory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class DisposableDirectory : TempDirectory, IDisposable { public DisposableDirectory(TempRoot root) : base(root) { } public void Dispose() { if (Path != null && Directory.Exists(Path)) { try { Directory.Delete(Path, recursive: true); } catch { } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class DisposableDirectory : TempDirectory, IDisposable { public DisposableDirectory(TempRoot root) : base(root) { } public void Dispose() { if (Path != null && Directory.Exists(Path)) { try { Directory.Delete(Path, recursive: true); } catch { } } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Analyzers/Core/Analyzers/RemoveUnnecessaryCast/AbstractRemoveUnnecessaryCastDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast { internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer< TLanguageKindEnum, TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TCastExpression : SyntaxNode { protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId, EnforceOnBuildValues.RemoveUnnecessaryCast, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)), isUnnecessary: true) { } protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; } protected abstract TextSpan GetFadeSpan(TCastExpression node); protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var diagnostic = TryRemoveCastExpression( context.SemanticModel, (TCastExpression)context.Node, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!IsUnnecessaryCast(model, node, cancellationToken)) { return null; } var tree = model.SyntaxTree; if (tree.OverlapsHiddenPosition(node.Span, cancellationToken)) { return null; } return Diagnostic.Create( Descriptor, node.SyntaxTree.GetLocation(GetFadeSpan(node)), ImmutableArray.Create(node.GetLocation())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast { internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer< TLanguageKindEnum, TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TCastExpression : SyntaxNode { protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId, EnforceOnBuildValues.RemoveUnnecessaryCast, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)), isUnnecessary: true) { } protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; } protected abstract TextSpan GetFadeSpan(TCastExpression node); protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var diagnostic = TryRemoveCastExpression( context.SemanticModel, (TCastExpression)context.Node, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!IsUnnecessaryCast(model, node, cancellationToken)) { return null; } var tree = model.SyntaxTree; if (tree.OverlapsHiddenPosition(node.Span, cancellationToken)) { return null; } return Diagnostic.Create( Descriptor, node.SyntaxTree.GetLocation(GetFadeSpan(node)), ImmutableArray.Create(node.GetLocation())); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests_ExpressionBody.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { // OverrideCompletionProviderTests overrides SetWorkspaceOptions to disable // expression-body members. This class does the opposite. public class OverrideCompletionProviderTests_ExpressionBody : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(OverrideCompletionProvider); protected override OptionSet WithChangedOptions(OptionSet options) { return options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyProperties() { var markupBeforeCommit = @"class B { public virtual int A { get; set; } class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A { get; set; } class C : B { public override int A { get => base.A$$; set => base.A = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyGetterOnlyProperty() { var markupBeforeCommit = @"class B { public virtual int A { get; } class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A { get; } class C : B { public override int A => base.A;$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyMethod() { var markupBeforeCommit = @"class B { public virtual int A() => 2; class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A() => 2; class C : B { public override int A() => base.A();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A()", expectedCodeAfterCommit); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { // OverrideCompletionProviderTests overrides SetWorkspaceOptions to disable // expression-body members. This class does the opposite. public class OverrideCompletionProviderTests_ExpressionBody : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(OverrideCompletionProvider); protected override OptionSet WithChangedOptions(OptionSet options) { return options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyProperties() { var markupBeforeCommit = @"class B { public virtual int A { get; set; } class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A { get; set; } class C : B { public override int A { get => base.A$$; set => base.A = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyGetterOnlyProperty() { var markupBeforeCommit = @"class B { public virtual int A { get; } class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A { get; } class C : B { public override int A => base.A;$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A", expectedCodeAfterCommit); } [WorkItem(16331, "https://github.com/dotnet/roslyn/issues/16334")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProducesExpressionBodyMethod() { var markupBeforeCommit = @"class B { public virtual int A() => 2; class C : B { override A$$ } }"; var expectedCodeAfterCommit = @"class B { public virtual int A() => 2; class C : B { public override int A() => base.A();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "A()", expectedCodeAfterCommit); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/Core/Portable/Utilities/CancellationSeries.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/project-system: // https://github.com/dotnet/project-system/blob/bdf69d5420ec8d894f5bf4c3d4692900b7f2479c/src/Microsoft.VisualStudio.ProjectSystem.Managed/Threading/Tasks/CancellationSeries.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; #if DEBUG using System.Diagnostics; #endif using System.Threading; namespace Roslyn.Utilities { /// <summary> /// Produces a series of <see cref="CancellationToken"/> objects such that requesting a new token /// causes the previously issued token to be cancelled. /// </summary> /// <remarks> /// <para>Consuming code is responsible for managing overlapping asynchronous operations.</para> /// <para>This class has a lock-free implementation to minimise latency and contention.</para> /// </remarks> internal sealed class CancellationSeries : IDisposable { private CancellationTokenSource? _cts = new(); private readonly CancellationToken _superToken; /// <summary> /// Initializes a new instance of <see cref="CancellationSeries"/>. /// </summary> /// <param name="token">An optional cancellation token that, when cancelled, cancels the last /// issued token and causes any subsequent tokens to be issued in a cancelled state.</param> public CancellationSeries(CancellationToken token = default) { _superToken = token; #if DEBUG _ctorStack = new StackTrace(); #endif } #if DEBUG private readonly StackTrace _ctorStack; ~CancellationSeries() { Contract.ThrowIfFalse( Environment.HasShutdownStarted || _cts == null, $"Instance of CancellationSeries not disposed before being finalized{Environment.NewLine}Stack at construction:{Environment.NewLine}{_ctorStack}"); } #endif /// <summary> /// Creates the next <see cref="CancellationToken"/> in the series, ensuring the last issued /// token (if any) is cancelled first. /// </summary> /// <param name="token">An optional cancellation token that, when cancelled, cancels the /// returned token.</param> /// <returns> /// A cancellation token that will be cancelled when either: /// <list type="bullet"> /// <item><see cref="CreateNext"/> is called again</item> /// <item>The token passed to this method (if any) is cancelled</item> /// <item>The token passed to the constructor (if any) is cancelled</item> /// <item><see cref="Dispose"/> is called</item> /// </list> /// </returns> /// <exception cref="ObjectDisposedException">This object has been disposed.</exception> public CancellationToken CreateNext(CancellationToken token = default) { var nextSource = CancellationTokenSource.CreateLinkedTokenSource(token, _superToken); // Obtain the token before exchange, as otherwise the CTS may be cancelled before // we request the Token, which will result in an ObjectDisposedException. // This way we would return a cancelled token, which is reasonable. var nextToken = nextSource.Token; // The following block is identical to Interlocked.Exchange, except no replacement is made if the current // field value is null (latch on null). This ensures state is not corrupted if CreateNext is called after // the object is disposed. var priorSource = Volatile.Read(ref _cts); while (priorSource is not null) { var candidate = Interlocked.CompareExchange(ref _cts, nextSource, priorSource); if (candidate == priorSource) { break; } else { priorSource = candidate; } } if (priorSource == null) { nextSource.Dispose(); throw new ObjectDisposedException(nameof(CancellationSeries)); } try { priorSource.Cancel(); } finally { // A registered action on the token may throw, which would surface here. // Ensure we always dispose the prior CTS. priorSource.Dispose(); } return nextToken; } public void Dispose() { #if DEBUG GC.SuppressFinalize(this); #endif var source = Interlocked.Exchange(ref _cts, null); if (source == null) { // Already disposed return; } try { source.Cancel(); } finally { source.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/project-system: // https://github.com/dotnet/project-system/blob/bdf69d5420ec8d894f5bf4c3d4692900b7f2479c/src/Microsoft.VisualStudio.ProjectSystem.Managed/Threading/Tasks/CancellationSeries.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; #if DEBUG using System.Diagnostics; #endif using System.Threading; namespace Roslyn.Utilities { /// <summary> /// Produces a series of <see cref="CancellationToken"/> objects such that requesting a new token /// causes the previously issued token to be cancelled. /// </summary> /// <remarks> /// <para>Consuming code is responsible for managing overlapping asynchronous operations.</para> /// <para>This class has a lock-free implementation to minimise latency and contention.</para> /// </remarks> internal sealed class CancellationSeries : IDisposable { private CancellationTokenSource? _cts = new(); private readonly CancellationToken _superToken; /// <summary> /// Initializes a new instance of <see cref="CancellationSeries"/>. /// </summary> /// <param name="token">An optional cancellation token that, when cancelled, cancels the last /// issued token and causes any subsequent tokens to be issued in a cancelled state.</param> public CancellationSeries(CancellationToken token = default) { _superToken = token; #if DEBUG _ctorStack = new StackTrace(); #endif } #if DEBUG private readonly StackTrace _ctorStack; ~CancellationSeries() { Contract.ThrowIfFalse( Environment.HasShutdownStarted || _cts == null, $"Instance of CancellationSeries not disposed before being finalized{Environment.NewLine}Stack at construction:{Environment.NewLine}{_ctorStack}"); } #endif /// <summary> /// Creates the next <see cref="CancellationToken"/> in the series, ensuring the last issued /// token (if any) is cancelled first. /// </summary> /// <param name="token">An optional cancellation token that, when cancelled, cancels the /// returned token.</param> /// <returns> /// A cancellation token that will be cancelled when either: /// <list type="bullet"> /// <item><see cref="CreateNext"/> is called again</item> /// <item>The token passed to this method (if any) is cancelled</item> /// <item>The token passed to the constructor (if any) is cancelled</item> /// <item><see cref="Dispose"/> is called</item> /// </list> /// </returns> /// <exception cref="ObjectDisposedException">This object has been disposed.</exception> public CancellationToken CreateNext(CancellationToken token = default) { var nextSource = CancellationTokenSource.CreateLinkedTokenSource(token, _superToken); // Obtain the token before exchange, as otherwise the CTS may be cancelled before // we request the Token, which will result in an ObjectDisposedException. // This way we would return a cancelled token, which is reasonable. var nextToken = nextSource.Token; // The following block is identical to Interlocked.Exchange, except no replacement is made if the current // field value is null (latch on null). This ensures state is not corrupted if CreateNext is called after // the object is disposed. var priorSource = Volatile.Read(ref _cts); while (priorSource is not null) { var candidate = Interlocked.CompareExchange(ref _cts, nextSource, priorSource); if (candidate == priorSource) { break; } else { priorSource = candidate; } } if (priorSource == null) { nextSource.Dispose(); throw new ObjectDisposedException(nameof(CancellationSeries)); } try { priorSource.Cancel(); } finally { // A registered action on the token may throw, which would surface here. // Ensure we always dispose the prior CTS. priorSource.Dispose(); } return nextToken; } public void Dispose() { #if DEBUG GC.SuppressFinalize(this); #endif var source = Interlocked.Exchange(ref _cts, null); if (source == null) { // Already disposed return; } try { source.Cancel(); } finally { source.Dispose(); } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex.DeclarationInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SyntaxTreeIndex { private readonly struct DeclarationInfo { public ImmutableArray<DeclaredSymbolInfo> DeclaredSymbolInfos { get; } public DeclarationInfo(ImmutableArray<DeclaredSymbolInfo> declaredSymbolInfos) => DeclaredSymbolInfos = declaredSymbolInfos; public void WriteTo(ObjectWriter writer) { writer.WriteInt32(DeclaredSymbolInfos.Length); foreach (var declaredSymbolInfo in DeclaredSymbolInfos) { declaredSymbolInfo.WriteTo(writer); } } public static DeclarationInfo? TryReadFrom(StringTable stringTable, ObjectReader reader) { try { var declaredSymbolCount = reader.ReadInt32(); var builder = ImmutableArray.CreateBuilder<DeclaredSymbolInfo>(declaredSymbolCount); for (var i = 0; i < declaredSymbolCount; i++) { builder.Add(DeclaredSymbolInfo.ReadFrom_ThrowsOnFailure(stringTable, reader)); } return new DeclarationInfo(builder.MoveToImmutable()); } catch (Exception) { } 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.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class SyntaxTreeIndex { private readonly struct DeclarationInfo { public ImmutableArray<DeclaredSymbolInfo> DeclaredSymbolInfos { get; } public DeclarationInfo(ImmutableArray<DeclaredSymbolInfo> declaredSymbolInfos) => DeclaredSymbolInfos = declaredSymbolInfos; public void WriteTo(ObjectWriter writer) { writer.WriteInt32(DeclaredSymbolInfos.Length); foreach (var declaredSymbolInfo in DeclaredSymbolInfos) { declaredSymbolInfo.WriteTo(writer); } } public static DeclarationInfo? TryReadFrom(StringTable stringTable, ObjectReader reader) { try { var declaredSymbolCount = reader.ReadInt32(); var builder = ImmutableArray.CreateBuilder<DeclaredSymbolInfo>(declaredSymbolCount); for (var i = 0; i < declaredSymbolCount; i++) { builder.Add(DeclaredSymbolInfo.ReadFrom_ThrowsOnFailure(stringTable, reader)); } return new DeclarationInfo(builder.MoveToImmutable()); } catch (Exception) { } return null; } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/CSharpTest/SymbolKey/SymbolKeyCompilationsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { // Add member N3.CGoo GetClass(); } namespace N3 { public class CGoo { public struct SGoo { // Update member public enum EGoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01"); var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01"); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind); Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] [WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] public void ExtendedPartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { public partial void M() { } public partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None)); } [Fact] public void RecursiveReferenceToConstructedGeneric() { var src1 = @"using System.Collections.Generic; class C { public void M<Z>(List<Z> list) { var v = list.Add(default(Z)); } }"; var comp1 = CreateCompilation(src1); var comp2 = CreateCompilation(src1); var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList(); var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList(); // First, make sure that all the symbols in this file resolve properly // to themselves. ResolveAndVerifySymbolList(symbols1, symbols2, comp1); // Now do this for the members of types we see. We want this // so we hit things like the members of the constructed type // List<Z> var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); ResolveAndVerifySymbolList(members1, members2, comp1); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DGoo(int p1); namespace N1.N2 { public interface IBase { } public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IGoo : IBase // add base interface { } namespace N3 { public class CGoo : IGoo // impl interface { private struct SGoo // change modifier { internal enum EGoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None); ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None)); } [WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules.First(); sym2 = comp2.Assembly.Modules.First(); ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules.First(); var module2 = compilation2.Assembly.Modules.First(); // different AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None)); AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true); var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); namespace N1.N2 { public interface IGoo { // Add member N3.CGoo GetClass(); } namespace N3 { public class CGoo { public struct SGoo { // Update member public enum EGoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilation(src1, assemblyName: "C2CErrorSymbolUnchanged01"); var comp2 = CreateCompilation(src2, assemblyName: "C2CErrorSymbolUnchanged01"); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(SymbolKind.ErrorType, symbol01.Kind); Assert.NotEqual(SymbolKind.ErrorType, symbol02.Kind); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] [WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] public void ExtendedPartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { public partial void M() { } public partial void M(); } } "; var comp = (Compilation)CreateCompilation(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = (Compilation)CreateCompilation(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as INamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None)); } [Fact] public void RecursiveReferenceToConstructedGeneric() { var src1 = @"using System.Collections.Generic; class C { public void M<Z>(List<Z> list) { var v = list.Add(default(Z)); } }"; var comp1 = CreateCompilation(src1); var comp2 = CreateCompilation(src1); var symbols1 = GetSourceSymbols(comp1, includeLocal: true).ToList(); var symbols2 = GetSourceSymbols(comp1, includeLocal: true).ToList(); // First, make sure that all the symbols in this file resolve properly // to themselves. ResolveAndVerifySymbolList(symbols1, symbols2, comp1); // Now do this for the members of types we see. We want this // so we hit things like the members of the constructed type // List<Z> var members1 = symbols1.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); var members2 = symbols2.OfType<INamespaceOrTypeSymbol>().SelectMany(n => n.GetMembers()).ToList(); ResolveAndVerifySymbolList(members1, members2, comp1); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DGoo(int p1); namespace N1.N2 { public interface IBase { } public interface IGoo { } namespace N3 { public class CGoo { public struct SGoo { public enum EGoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DGoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IGoo : IBase // add base interface { } namespace N3 { public class CGoo : IGoo // impl interface { private struct SGoo // change modifier { internal enum EGoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as INamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilation(src1, assemblyName: "Test"); var comp2 = CreateCompilation(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = (Compilation)CreateCompilation(src1, assemblyName: "Test"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as INamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None); ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as INamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as INamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None)); } [WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules.First(); sym2 = comp2.Assembly.Modules.First(); ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly1"); var compilation2 = (Compilation)CreateCompilation(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules.First(); var module2 = compilation2.Assembly.Modules.First(); // different AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None)); AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = (Compilation)CreateCompilation(src, assemblyName: "Assembly"); var comp2 = (Compilation)CreateCompilation(src2, assemblyName: "Assembly"); ISymbol sym1 = comp1.Assembly; ISymbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true); var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #endregion } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/VisualStudio/Core/Def/Implementation/HierarchyItemToProjectIdMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IHierarchyItemToProjectIdMap), ServiceLayer.Host), Shared] internal class HierarchyItemToProjectIdMap : IHierarchyItemToProjectIdMap { private readonly VisualStudioWorkspaceImpl _workspace; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HierarchyItemToProjectIdMap(VisualStudioWorkspaceImpl workspace) => _workspace = workspace; public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId) { // A project node is represented in two different hierarchies: the solution's IVsHierarchy (where it is a leaf node) // and the project's own IVsHierarchy (where it is the root node). The IVsHierarchyItem joins them together for the // purpose of creating the tree displayed in Solution Explorer. The project's hierarchy is what is passed from the // project system to the language service, so that's the one the one to query here. To do that we need to get // the "nested" hierarchy from the IVsHierarchyItem. var nestedHierarchy = hierarchyItem.HierarchyIdentity.NestedHierarchy; // First filter the projects by matching up properties on the input hierarchy against properties on each // project's hierarchy. var candidateProjects = _workspace.CurrentSolution.Projects .Where(p => { // We're about to access various properties of the IVsHierarchy associated with the project. // The properties supported and the interpretation of their values varies from one project system // to another. This code is designed with C# and VB in mind, so we need to filter out everything // else. if (p.Language != LanguageNames.CSharp && p.Language != LanguageNames.VisualBasic) { return false; } var hierarchy = _workspace.GetHierarchy(p.Id); return hierarchy == nestedHierarchy; }) .ToArray(); // If we only have one candidate then no further checks are required. if (candidateProjects.Length == 1) { projectId = candidateProjects[0].Id; return true; } // For CPS projects, we may have a string we extracted from a $TFM-prefixed capability; compare that to the string we're given // from CPS to see if this matches. if (targetFrameworkMoniker != null) { var matchingProject = candidateProjects.FirstOrDefault(p => _workspace.TryGetDependencyNodeTargetIdentifier(p.Id) == targetFrameworkMoniker); if (matchingProject != null) { projectId = matchingProject.Id; return true; } } // If we have multiple candidates then we might be dealing with Web Application Projects. In this case // there will be one main project plus one project for each open aspx/cshtml/vbhtml file, all with // identical properties on their hierarchies. We can find the main project by taking the first project // without a ContainedDocument. foreach (var candidateProject in candidateProjects) { if (!candidateProject.DocumentIds.Any(id => ContainedDocument.TryGetContainedDocument(id) != null)) { projectId = candidateProject.Id; return true; } } projectId = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IHierarchyItemToProjectIdMap), ServiceLayer.Host), Shared] internal class HierarchyItemToProjectIdMap : IHierarchyItemToProjectIdMap { private readonly VisualStudioWorkspaceImpl _workspace; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public HierarchyItemToProjectIdMap(VisualStudioWorkspaceImpl workspace) => _workspace = workspace; public bool TryGetProjectId(IVsHierarchyItem hierarchyItem, string? targetFrameworkMoniker, [NotNullWhen(true)] out ProjectId? projectId) { // A project node is represented in two different hierarchies: the solution's IVsHierarchy (where it is a leaf node) // and the project's own IVsHierarchy (where it is the root node). The IVsHierarchyItem joins them together for the // purpose of creating the tree displayed in Solution Explorer. The project's hierarchy is what is passed from the // project system to the language service, so that's the one the one to query here. To do that we need to get // the "nested" hierarchy from the IVsHierarchyItem. var nestedHierarchy = hierarchyItem.HierarchyIdentity.NestedHierarchy; // First filter the projects by matching up properties on the input hierarchy against properties on each // project's hierarchy. var candidateProjects = _workspace.CurrentSolution.Projects .Where(p => { // We're about to access various properties of the IVsHierarchy associated with the project. // The properties supported and the interpretation of their values varies from one project system // to another. This code is designed with C# and VB in mind, so we need to filter out everything // else. if (p.Language != LanguageNames.CSharp && p.Language != LanguageNames.VisualBasic) { return false; } var hierarchy = _workspace.GetHierarchy(p.Id); return hierarchy == nestedHierarchy; }) .ToArray(); // If we only have one candidate then no further checks are required. if (candidateProjects.Length == 1) { projectId = candidateProjects[0].Id; return true; } // For CPS projects, we may have a string we extracted from a $TFM-prefixed capability; compare that to the string we're given // from CPS to see if this matches. if (targetFrameworkMoniker != null) { var matchingProject = candidateProjects.FirstOrDefault(p => _workspace.TryGetDependencyNodeTargetIdentifier(p.Id) == targetFrameworkMoniker); if (matchingProject != null) { projectId = matchingProject.Id; return true; } } // If we have multiple candidates then we might be dealing with Web Application Projects. In this case // there will be one main project plus one project for each open aspx/cshtml/vbhtml file, all with // identical properties on their hierarchies. We can find the main project by taking the first project // without a ContainedDocument. foreach (var candidateProject in candidateProjects) { if (!candidateProject.DocumentIds.Any(id => ContainedDocument.TryGetContainedDocument(id) != null)) { projectId = candidateProject.Id; return true; } } projectId = null; return false; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Symbols/Source/SynthesizedAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols { /// <summary> /// Class to represent a synthesized attribute /// </summary> internal sealed class SynthesizedAttributeData : SourceAttributeData { internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) : base( applicationNode: null, attributeClass: wellKnownMember.ContainingType, attributeConstructor: wellKnownMember, constructorArguments: arguments, constructorArgumentsSourceIndices: default, namedArguments: namedArguments, hasErrors: false, isConditionallyOmitted: false) { Debug.Assert((object)wellKnownMember != null); Debug.Assert(!arguments.IsDefault); Debug.Assert(!namedArguments.IsDefault); // Frequently empty though. } internal SynthesizedAttributeData(SourceAttributeData original) : base( applicationNode: original.ApplicationSyntaxReference, attributeClass: original.AttributeClass, attributeConstructor: original.AttributeConstructor, constructorArguments: original.CommonConstructorArguments, constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices, namedArguments: original.CommonNamedArguments, hasErrors: original.HasErrors, isConditionallyOmitted: original.IsConditionallyOmitted) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Symbols { /// <summary> /// Class to represent a synthesized attribute /// </summary> internal sealed class SynthesizedAttributeData : SourceAttributeData { internal SynthesizedAttributeData(MethodSymbol wellKnownMember, ImmutableArray<TypedConstant> arguments, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) : base( applicationNode: null, attributeClass: wellKnownMember.ContainingType, attributeConstructor: wellKnownMember, constructorArguments: arguments, constructorArgumentsSourceIndices: default, namedArguments: namedArguments, hasErrors: false, isConditionallyOmitted: false) { Debug.Assert((object)wellKnownMember != null); Debug.Assert(!arguments.IsDefault); Debug.Assert(!namedArguments.IsDefault); // Frequently empty though. } internal SynthesizedAttributeData(SourceAttributeData original) : base( applicationNode: original.ApplicationSyntaxReference, attributeClass: original.AttributeClass, attributeConstructor: original.AttributeConstructor, constructorArguments: original.CommonConstructorArguments, constructorArgumentsSourceIndices: original.ConstructorArgumentsSourceIndices, namedArguments: original.CommonNamedArguments, hasErrors: original.HasErrors, isConditionallyOmitted: original.IsConditionallyOmitted) { } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/PropertyDocumentationCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PropertyDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public PropertyDocumentationCommentTests() { _compilation = CreateCompilation(@"namespace Acme { class Widget: IProcess { public int Width { get { } set { } } public int this[int i] { get { } set { } } public int this[string s, int i] { get { } set { } } } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestProperty() { Assert.Equal("P:Acme.Widget.Width", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("Width").Single().GetDocumentationCommentId()); } [Fact] public void TestIndexer1() { Assert.Equal("P:Acme.Widget.Item(System.Int32)", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("this[]")[0].GetDocumentationCommentId()); } [Fact] public void TestIndexer2() { Assert.Equal("P:Acme.Widget.Item(System.String,System.Int32)", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("this[]")[1].GetDocumentationCommentId()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class PropertyDocumentationCommentTests : CSharpTestBase { private readonly CSharpCompilation _compilation; private readonly NamespaceSymbol _acmeNamespace; private readonly NamedTypeSymbol _widgetClass; public PropertyDocumentationCommentTests() { _compilation = CreateCompilation(@"namespace Acme { class Widget: IProcess { public int Width { get { } set { } } public int this[int i] { get { } set { } } public int this[string s, int i] { get { } set { } } } } "); _acmeNamespace = (NamespaceSymbol)_compilation.GlobalNamespace.GetMembers("Acme").Single(); _widgetClass = _acmeNamespace.GetTypeMembers("Widget").Single(); } [Fact] public void TestProperty() { Assert.Equal("P:Acme.Widget.Width", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("Width").Single().GetDocumentationCommentId()); } [Fact] public void TestIndexer1() { Assert.Equal("P:Acme.Widget.Item(System.Int32)", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("this[]")[0].GetDocumentationCommentId()); } [Fact] public void TestIndexer2() { Assert.Equal("P:Acme.Widget.Item(System.String,System.Int32)", _acmeNamespace.GetTypeMembers("Widget").Single() .GetMembers("this[]")[1].GetDocumentationCommentId()); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/CSharp/Portable/Structure/Providers/RegionDirectiveStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class RegionDirectiveStructureProvider : AbstractSyntaxNodeStructureProvider<RegionDirectiveTriviaSyntax> { private static string GetBannerText(DirectiveTriviaSyntax simpleDirective) { var kw = simpleDirective.DirectiveNameToken; var prefixLength = kw.Span.End - simpleDirective.Span.Start; var text = simpleDirective.ToString().Substring(prefixLength).Trim(); if (text.Length == 0) { return simpleDirective.HashToken.ToString() + kw.ToString(); } else { return text; } } protected override void CollectBlockSpans( RegionDirectiveTriviaSyntax regionDirective, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var match = regionDirective.GetMatchingDirective(cancellationToken); if (match != null) { // Always auto-collapse regions for Metadata As Source. These generated files only have one region at // the top of the file, which has content like the following: // // #region Assembly System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // // C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Runtime.dll // #endregion // // For other files, auto-collapse regions based on the user option. var autoCollapse = optionProvider.IsMetadataAsSource || optionProvider.GetOption( BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(regionDirective.SpanStart, match.Span.End), type: BlockTypes.PreprocessorRegion, bannerText: GetBannerText(regionDirective), autoCollapse: autoCollapse, isDefaultCollapsed: !optionProvider.IsMetadataAsSource)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class RegionDirectiveStructureProvider : AbstractSyntaxNodeStructureProvider<RegionDirectiveTriviaSyntax> { private static string GetBannerText(DirectiveTriviaSyntax simpleDirective) { var kw = simpleDirective.DirectiveNameToken; var prefixLength = kw.Span.End - simpleDirective.Span.Start; var text = simpleDirective.ToString().Substring(prefixLength).Trim(); if (text.Length == 0) { return simpleDirective.HashToken.ToString() + kw.ToString(); } else { return text; } } protected override void CollectBlockSpans( RegionDirectiveTriviaSyntax regionDirective, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var match = regionDirective.GetMatchingDirective(cancellationToken); if (match != null) { // Always auto-collapse regions for Metadata As Source. These generated files only have one region at // the top of the file, which has content like the following: // // #region Assembly System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // // C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Runtime.dll // #endregion // // For other files, auto-collapse regions based on the user option. var autoCollapse = optionProvider.IsMetadataAsSource || optionProvider.GetOption( BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(regionDirective.SpanStart, match.Span.End), type: BlockTypes.PreprocessorRegion, bannerText: GetBannerText(regionDirective), autoCollapse: autoCollapse, isDefaultCollapsed: !optionProvider.IsMetadataAsSource)); } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmProcess.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger { public class DkmProcess { public readonly DkmEngineSettings EngineSettings = new DkmEngineSettings(); private readonly bool _nativeDebuggingEnabled; public DkmProcess(bool enableNativeDebugging) { _nativeDebuggingEnabled = enableNativeDebugging; } public DkmRuntimeInstance GetNativeRuntimeInstance() { if (!_nativeDebuggingEnabled) { throw new DkmException(DkmExceptionCode.E_XAPI_DATA_ITEM_NOT_FOUND); } return null; // Value isn't required for testing } } public class DkmThread { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger { public class DkmProcess { public readonly DkmEngineSettings EngineSettings = new DkmEngineSettings(); private readonly bool _nativeDebuggingEnabled; public DkmProcess(bool enableNativeDebugging) { _nativeDebuggingEnabled = enableNativeDebugging; } public DkmRuntimeInstance GetNativeRuntimeInstance() { if (!_nativeDebuggingEnabled) { throw new DkmException(DkmExceptionCode.E_XAPI_DATA_ITEM_NOT_FOUND); } return null; // Value isn't required for testing } } public class DkmThread { } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/LanguageServer/ProtocolUnitTests/ProjectContext/GetTextDocumentWithContextHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.ProjectContext { public class GetTextDocumentWithContextHandlerTests : AbstractLanguageServerProtocolTests { [Fact] public async Task SingleDocumentReturnsSingleContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj""> <Document FilePath = ""C:\C.cs"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Equal(0, result!.DefaultIndex); var context = Assert.Single(result.ProjectContexts); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(testLspServer.GetCurrentSolution().ProjectIds.Single()), context.Id); Assert.Equal(LSP.ProjectContextKind.CSharp, context.Kind); Assert.Equal("CSProj", context.Label); } [Fact] public async Task MultipleDocumentsReturnsMultipleContexts() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Collection(result!.ProjectContexts.OrderBy(c => c.Label), c => Assert.Equal("CSProj1", c.Label), c => Assert.Equal("CSProj2", c.Label)); } [Fact] public async Task SwitchingContextsChangesDefaultContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); // Ensure the documents are open so we can change contexts foreach (var document in testLspServer.TestWorkspace.Documents) { _ = document.GetOpenTextContainer(); } var documentUri = locations["caret"].Single().Uri; foreach (var project in testLspServer.GetCurrentSolution().Projects) { testLspServer.TestWorkspace.SetDocumentContext(project.DocumentIds.Single()); var result = await RunGetProjectContext(testLspServer, documentUri); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(project.Id), result!.ProjectContexts[result.DefaultIndex].Id); Assert.Equal(project.Name, result!.ProjectContexts[result.DefaultIndex].Label); } } private static async Task<LSP.ActiveProjectContexts?> RunGetProjectContext(TestLspServer testLspServer, Uri uri) { return await testLspServer.ExecuteRequestAsync<LSP.GetTextDocumentWithContextParams, LSP.ActiveProjectContexts?>(LSP.MSLSPMethods.ProjectContextsName, CreateGetProjectContextParams(uri), new LSP.ClientCapabilities(), clientName: null, cancellationToken: CancellationToken.None); } private static LSP.GetTextDocumentWithContextParams CreateGetProjectContextParams(Uri uri) => new LSP.GetTextDocumentWithContextParams() { TextDocument = new LSP.TextDocumentItem { Uri = uri } }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.ProjectContext { public class GetTextDocumentWithContextHandlerTests : AbstractLanguageServerProtocolTests { [Fact] public async Task SingleDocumentReturnsSingleContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj""> <Document FilePath = ""C:\C.cs"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Equal(0, result!.DefaultIndex); var context = Assert.Single(result.ProjectContexts); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(testLspServer.GetCurrentSolution().ProjectIds.Single()), context.Id); Assert.Equal(LSP.ProjectContextKind.CSharp, context.Kind); Assert.Equal("CSProj", context.Label); } [Fact] public async Task MultipleDocumentsReturnsMultipleContexts() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1"">{|caret:|}</Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); var documentUri = locations["caret"].Single().Uri; var result = await RunGetProjectContext(testLspServer, documentUri); Assert.NotNull(result); Assert.Collection(result!.ProjectContexts.OrderBy(c => c.Label), c => Assert.Equal("CSProj1", c.Label), c => Assert.Equal("CSProj2", c.Label)); } [Fact] public async Task SwitchingContextsChangesDefaultContext() { var workspaceXml = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj1""> <Document FilePath=""C:\C.cs"">{|caret:|}</Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""CSProj2""> <Document IsLinkFile=""true"" LinkFilePath=""C:\C.cs"" LinkAssemblyName=""CSProj1""></Document> </Project> </Workspace>"; using var testLspServer = CreateXmlTestLspServer(workspaceXml, out var locations); // Ensure the documents are open so we can change contexts foreach (var document in testLspServer.TestWorkspace.Documents) { _ = document.GetOpenTextContainer(); } var documentUri = locations["caret"].Single().Uri; foreach (var project in testLspServer.GetCurrentSolution().Projects) { testLspServer.TestWorkspace.SetDocumentContext(project.DocumentIds.Single()); var result = await RunGetProjectContext(testLspServer, documentUri); Assert.Equal(ProtocolConversions.ProjectIdToProjectContextId(project.Id), result!.ProjectContexts[result.DefaultIndex].Id); Assert.Equal(project.Name, result!.ProjectContexts[result.DefaultIndex].Label); } } private static async Task<LSP.ActiveProjectContexts?> RunGetProjectContext(TestLspServer testLspServer, Uri uri) { return await testLspServer.ExecuteRequestAsync<LSP.GetTextDocumentWithContextParams, LSP.ActiveProjectContexts?>(LSP.MSLSPMethods.ProjectContextsName, CreateGetProjectContextParams(uri), new LSP.ClientCapabilities(), clientName: null, cancellationToken: CancellationToken.None); } private static LSP.GetTextDocumentWithContextParams CreateGetProjectContextParams(Uri uri) => new LSP.GetTextDocumentWithContextParams() { TextDocument = new LSP.TextDocumentItem { Uri = uri } }; } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveEvaluatorLanguageInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal abstract class InteractiveEvaluatorLanguageInfoProvider { public abstract string LanguageName { get; } public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports); public abstract ParseOptions ParseOptions { get; } public abstract CommandLineParser CommandLineParser { get; } public abstract bool IsCompleteSubmission(string text); public abstract string InteractiveResponseFileName { get; } public abstract Type ReplServiceProviderType { 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.Immutable; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal abstract class InteractiveEvaluatorLanguageInfoProvider { public abstract string LanguageName { get; } public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports); public abstract ParseOptions ParseOptions { get; } public abstract CommandLineParser CommandLineParser { get; } public abstract bool IsCompleteSubmission(string text); public abstract string InteractiveResponseFileName { get; } public abstract Type ReplServiceProviderType { get; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Tools/IdeCoreBenchmarks/SegmentedArrayBenchmarks_Indexer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Collections; namespace IdeCoreBenchmarks { [DisassemblyDiagnoser] public class SegmentedArrayBenchmarks_Indexer { private int[] _values = null!; private object?[] _valuesObject = null!; private SegmentedArray<int> _segmentedValues; private SegmentedArray<object?> _segmentedValuesObject; [Params(100000)] public int Count { get; set; } [GlobalSetup] public void GlobalSetup() { _values = new int[Count]; _valuesObject = new object?[Count]; _segmentedValues = new SegmentedArray<int>(Count); _segmentedValuesObject = new SegmentedArray<object?>(Count); } [Benchmark(Description = "int[]", Baseline = true)] public void ShiftAllArray() { for (var i = 0; i < _values.Length - 1; i++) { _values[i] = _values[i + 1]; } _values[^1] = 0; } [Benchmark(Description = "int[] (Copy)")] public void ShiftAllViaArrayCopy() { Array.Copy(_values, 1, _values, 0, _values.Length - 1); _values[^1] = 0; } [Benchmark(Description = "object[]")] public void ShiftAllArrayObject() { for (var i = 0; i < _valuesObject.Length - 1; i++) { _valuesObject[i] = _valuesObject[i + 1]; } _valuesObject[^1] = null; } [Benchmark(Description = "object[] (Copy)")] public void ShiftAllObjectViaArrayCopy() { Array.Copy(_valuesObject, 1, _valuesObject, 0, _valuesObject.Length - 1); _valuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<int>")] public void ShiftAllSegmented() { for (var i = 0; i < _segmentedValues.Length - 1; i++) { _segmentedValues[i] = _segmentedValues[i + 1]; } _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<int> (Copy)")] public void ShiftAllViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValues, 1, _segmentedValues, 0, _segmentedValues.Length - 1); _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<object>")] public void ShiftAllSegmentedObject() { for (var i = 0; i < _segmentedValuesObject.Length - 1; i++) { _segmentedValuesObject[i] = _segmentedValuesObject[i + 1]; } _segmentedValuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<object> (Copy)")] public void ShiftAllObjectViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValuesObject, 1, _segmentedValuesObject, 0, _segmentedValuesObject.Length - 1); _segmentedValuesObject[^1] = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using BenchmarkDotNet.Attributes; using Microsoft.CodeAnalysis.Collections; namespace IdeCoreBenchmarks { [DisassemblyDiagnoser] public class SegmentedArrayBenchmarks_Indexer { private int[] _values = null!; private object?[] _valuesObject = null!; private SegmentedArray<int> _segmentedValues; private SegmentedArray<object?> _segmentedValuesObject; [Params(100000)] public int Count { get; set; } [GlobalSetup] public void GlobalSetup() { _values = new int[Count]; _valuesObject = new object?[Count]; _segmentedValues = new SegmentedArray<int>(Count); _segmentedValuesObject = new SegmentedArray<object?>(Count); } [Benchmark(Description = "int[]", Baseline = true)] public void ShiftAllArray() { for (var i = 0; i < _values.Length - 1; i++) { _values[i] = _values[i + 1]; } _values[^1] = 0; } [Benchmark(Description = "int[] (Copy)")] public void ShiftAllViaArrayCopy() { Array.Copy(_values, 1, _values, 0, _values.Length - 1); _values[^1] = 0; } [Benchmark(Description = "object[]")] public void ShiftAllArrayObject() { for (var i = 0; i < _valuesObject.Length - 1; i++) { _valuesObject[i] = _valuesObject[i + 1]; } _valuesObject[^1] = null; } [Benchmark(Description = "object[] (Copy)")] public void ShiftAllObjectViaArrayCopy() { Array.Copy(_valuesObject, 1, _valuesObject, 0, _valuesObject.Length - 1); _valuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<int>")] public void ShiftAllSegmented() { for (var i = 0; i < _segmentedValues.Length - 1; i++) { _segmentedValues[i] = _segmentedValues[i + 1]; } _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<int> (Copy)")] public void ShiftAllViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValues, 1, _segmentedValues, 0, _segmentedValues.Length - 1); _segmentedValues[^1] = 0; } [Benchmark(Description = "SegmentedArray<object>")] public void ShiftAllSegmentedObject() { for (var i = 0; i < _segmentedValuesObject.Length - 1; i++) { _segmentedValuesObject[i] = _segmentedValuesObject[i + 1]; } _segmentedValuesObject[^1] = null; } [Benchmark(Description = "SegmentedArray<object> (Copy)")] public void ShiftAllObjectViaSegmentedArrayCopy() { SegmentedArray.Copy(_segmentedValuesObject, 1, _segmentedValuesObject, 0, _segmentedValuesObject.Length - 1); _segmentedValuesObject[^1] = null; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/Compilation/CommonSyntaxAndDeclarationManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal abstract class CommonSyntaxAndDeclarationManager { internal readonly ImmutableArray<SyntaxTree> ExternalSyntaxTrees; internal readonly string ScriptClassName; internal readonly SourceReferenceResolver Resolver; internal readonly CommonMessageProvider MessageProvider; internal readonly bool IsSubmission; public CommonSyntaxAndDeclarationManager( ImmutableArray<SyntaxTree> externalSyntaxTrees, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission) { this.ExternalSyntaxTrees = externalSyntaxTrees; this.ScriptClassName = scriptClassName ?? ""; this.Resolver = resolver; this.MessageProvider = messageProvider; this.IsSubmission = isSubmission; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal abstract class CommonSyntaxAndDeclarationManager { internal readonly ImmutableArray<SyntaxTree> ExternalSyntaxTrees; internal readonly string ScriptClassName; internal readonly SourceReferenceResolver Resolver; internal readonly CommonMessageProvider MessageProvider; internal readonly bool IsSubmission; public CommonSyntaxAndDeclarationManager( ImmutableArray<SyntaxTree> externalSyntaxTrees, string scriptClassName, SourceReferenceResolver resolver, CommonMessageProvider messageProvider, bool isSubmission) { this.ExternalSyntaxTrees = externalSyntaxTrees; this.ScriptClassName = scriptClassName ?? ""; this.Resolver = resolver; this.MessageProvider = messageProvider; this.IsSubmission = isSubmission; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/Remote/ServiceHub/Services/NavigateToSearch/RemoteNavigateToSearchService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteNavigateToSearchService : BrokeredServiceBase, IRemoteNavigateToSearchService { internal sealed class Factory : FactoryBase<IRemoteNavigateToSearchService, IRemoteNavigateToSearchService.ICallback> { protected override IRemoteNavigateToSearchService CreateService( in ServiceConstructionArguments arguments, RemoteCallback<IRemoteNavigateToSearchService.ICallback> callback) => new RemoteNavigateToSearchService(arguments, callback); } private readonly RemoteCallback<IRemoteNavigateToSearchService.ICallback> _callback; public RemoteNavigateToSearchService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteNavigateToSearchService.ICallback> callback) : base(arguments) { _callback = callback; } private Func<RoslynNavigateToItem, Task> GetCallback( RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return async i => await _callback.InvokeAsync((callback, c) => callback.OnResultFoundAsync(callbackId, i), cancellationToken).ConfigureAwait(false); } public ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // All we need to do is request the solution. This will ensure that all assets are // pulled over from the host side to the remote side. Once this completes, the next // call to SearchFullyLoadedDocumentAsync or SearchFullyLoadedProjectAsync will be // quick as very little will need to by sync'ed over. await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchFullyLoadedDocumentAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); var callback = GetCallback(callbackId, cancellationToken); await AbstractNavigateToSearchService.SearchFullyLoadedDocumentInCurrentProcessAsync( document, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchFullyLoadedProjectAsync( PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray<DocumentId> priorityDocumentIds, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var project = solution.GetRequiredProject(projectId); var callback = GetCallback(callbackId, cancellationToken); var priorityDocuments = priorityDocumentIds.SelectAsArray(d => solution.GetRequiredDocument(d)); await AbstractNavigateToSearchService.SearchFullyLoadedProjectInCurrentProcessAsync( project, priorityDocuments, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchCachedDocumentsAsync(ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // Intentionally do not call GetSolutionAsync here. We do not want the cost of // synchronizing the solution over to the remote side. Instead, we just directly // check whatever cached data we have from the previous vs session. var callback = GetCallback(callbackId, cancellationToken); await AbstractNavigateToSearchService.SearchCachedDocumentsInCurrentProcessAsync( GetWorkspace(), documentKeys, priorityDocumentKeys, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteNavigateToSearchService : BrokeredServiceBase, IRemoteNavigateToSearchService { internal sealed class Factory : FactoryBase<IRemoteNavigateToSearchService, IRemoteNavigateToSearchService.ICallback> { protected override IRemoteNavigateToSearchService CreateService( in ServiceConstructionArguments arguments, RemoteCallback<IRemoteNavigateToSearchService.ICallback> callback) => new RemoteNavigateToSearchService(arguments, callback); } private readonly RemoteCallback<IRemoteNavigateToSearchService.ICallback> _callback; public RemoteNavigateToSearchService(in ServiceConstructionArguments arguments, RemoteCallback<IRemoteNavigateToSearchService.ICallback> callback) : base(arguments) { _callback = callback; } private Func<RoslynNavigateToItem, Task> GetCallback( RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return async i => await _callback.InvokeAsync((callback, c) => callback.OnResultFoundAsync(callbackId, i), cancellationToken).ConfigureAwait(false); } public ValueTask HydrateAsync(PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // All we need to do is request the solution. This will ensure that all assets are // pulled over from the host side to the remote side. Once this completes, the next // call to SearchFullyLoadedDocumentAsync or SearchFullyLoadedProjectAsync will be // quick as very little will need to by sync'ed over. await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchFullyLoadedDocumentAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetRequiredDocument(documentId); var callback = GetCallback(callbackId, cancellationToken); await AbstractNavigateToSearchService.SearchFullyLoadedDocumentInCurrentProcessAsync( document, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchFullyLoadedProjectAsync( PinnedSolutionInfo solutionInfo, ProjectId projectId, ImmutableArray<DocumentId> priorityDocumentIds, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var project = solution.GetRequiredProject(projectId); var callback = GetCallback(callbackId, cancellationToken); var priorityDocuments = priorityDocumentIds.SelectAsArray(d => solution.GetRequiredDocument(d)); await AbstractNavigateToSearchService.SearchFullyLoadedProjectInCurrentProcessAsync( project, priorityDocuments, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } public ValueTask SearchCachedDocumentsAsync(ImmutableArray<DocumentKey> documentKeys, ImmutableArray<DocumentKey> priorityDocumentKeys, string searchPattern, ImmutableArray<string> kinds, RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { // Intentionally do not call GetSolutionAsync here. We do not want the cost of // synchronizing the solution over to the remote side. Instead, we just directly // check whatever cached data we have from the previous vs session. var callback = GetCallback(callbackId, cancellationToken); await AbstractNavigateToSearchService.SearchCachedDocumentsInCurrentProcessAsync( GetWorkspace(), documentKeys, priorityDocumentKeys, searchPattern, kinds.ToImmutableHashSet(), callback, cancellationToken).ConfigureAwait(false); }, cancellationToken); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Symbols/PublicModel/AliasSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class AliasSymbol : Symbol, IAliasSymbol { private readonly Symbols.AliasSymbol _underlying; public AliasSymbol(Symbols.AliasSymbol underlying) { RoslynDebug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceOrTypeSymbol IAliasSymbol.Target { get { return _underlying.Target.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitAlias(this); } protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default { return visitor.VisitAlias(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class AliasSymbol : Symbol, IAliasSymbol { private readonly Symbols.AliasSymbol _underlying; public AliasSymbol(Symbols.AliasSymbol underlying) { RoslynDebug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; INamespaceOrTypeSymbol IAliasSymbol.Target { get { return _underlying.Target.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitAlias(this); } protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default { return visitor.VisitAlias(this); } #endregion } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Test/Utilities/CSharp/CSharpTrackingDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { public class CSharpTrackingDiagnosticAnalyzer : TrackingDiagnosticAnalyzer<SyntaxKind> { private static readonly Regex s_omittedSyntaxKindRegex = new Regex(@"Using|Extern|Parameter|Constraint|Specifier|Initializer|Global|Method|Destructor|MemberBindingExpression|ElementBindingExpression|ArrowExpressionClause|NameOfExpression"); protected override bool IsOnCodeBlockSupported(SymbolKind symbolKind, MethodKind methodKind, bool returnsVoid) { return base.IsOnCodeBlockSupported(symbolKind, methodKind, returnsVoid) && methodKind != MethodKind.EventRaise; } protected override bool IsAnalyzeNodeSupported(SyntaxKind syntaxKind) { return base.IsAnalyzeNodeSupported(syntaxKind) && !s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities { public class CSharpTrackingDiagnosticAnalyzer : TrackingDiagnosticAnalyzer<SyntaxKind> { private static readonly Regex s_omittedSyntaxKindRegex = new Regex(@"Using|Extern|Parameter|Constraint|Specifier|Initializer|Global|Method|Destructor|MemberBindingExpression|ElementBindingExpression|ArrowExpressionClause|NameOfExpression"); protected override bool IsOnCodeBlockSupported(SymbolKind symbolKind, MethodKind methodKind, bool returnsVoid) { return base.IsOnCodeBlockSupported(symbolKind, methodKind, returnsVoid) && methodKind != MethodKind.EventRaise; } protected override bool IsAnalyzeNodeSupported(SyntaxKind syntaxKind) { return base.IsAnalyzeNodeSupported(syntaxKind) && !s_omittedSyntaxKindRegex.IsMatch(syntaxKind.ToString()); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/CommandLine/CSharpCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpCompiler : CommonCompiler { internal const string ResponseFileName = "csc.rsp"; private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; private readonly string? _tempDirectory; protected CSharpCompiler(CSharpCommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader) : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader) { _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); _tempDirectory = buildPaths.TempDirectory; } public override DiagnosticFormatter DiagnosticFormatter { get { return _diagnosticFormatter; } } protected internal new CSharpCommandLineArguments Arguments { get { return (CSharpCommandLineArguments)base.Arguments; } } public override Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions) { var parseOptions = Arguments.ParseOptions; // We compute script parse options once so we don't have to do it repeatedly in // case there are many script files. var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); bool hadErrors = false; var sourceFiles = Arguments.SourceFiles; var trees = new SyntaxTree?[sourceFiles.Length]; var normalizedFilePaths = new string?[sourceFiles.Length]; var diagnosticBag = DiagnosticBag.GetInstance(); if (Arguments.CompilationOptions.ConcurrentBuild) { RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); }), CancellationToken.None); } else { for (int i = 0; i < sourceFiles.Length; i++) { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); } } // If errors had been reported in ParseFile, while trying to read files, then we should simply exit. if (ReportDiagnostics(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger, compilation: null)) { Debug.Assert(hadErrors); return null; } var diagnostics = new List<DiagnosticInfo>(); var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sourceFiles.Length; i++) { var normalizedFilePath = normalizedFilePaths[i]; Debug.Assert(normalizedFilePath != null); Debug.Assert(sourceFiles[i].IsInputRedirected || PathUtilities.IsAbsolute(normalizedFilePath)); if (!uniqueFilePaths.Add(normalizedFilePath)) { // warning CS2002: Source file '{0}' specified multiple times diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded, Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath))); trees[i] = null; } } if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger is object); foreach (var path in uniqueFilePaths) { touchedFilesLogger.AddRead(path); } } var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; var appConfigPath = this.Arguments.AppConfigPath; if (appConfigPath != null) { try { using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } if (touchedFilesLogger != null) { touchedFilesLogger.AddRead(appConfigPath); } } catch (Exception ex) { diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message)); } } var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger); var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger); MetadataReferenceResolver referenceDirectiveResolver; var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null)) { return null; } var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory); var optionsProvider = new CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalConfigOptions); return CSharpCompilation.Create( Arguments.CompilationName, trees.WhereNotNull(), resolvedReferences, Arguments.CompilationOptions .WithMetadataReferenceResolver(referenceDirectiveResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithXmlReferenceResolver(xmlFileResolver) .WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)) .WithSourceReferenceResolver(sourceFileResolver) .WithSyntaxTreeOptionsProvider(optionsProvider)); } private SyntaxTree? ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string? normalizedFilePath) { var fileDiagnostics = new List<DiagnosticInfo>(); var content = TryReadFileContent(file, fileDiagnostics, out normalizedFilePath); if (content == null) { foreach (var info in fileDiagnostics) { diagnostics.Add(MessageProvider.CreateDiagnostic(info)); } fileDiagnostics.Clear(); addedDiagnostics = true; return null; } else { Debug.Assert(fileDiagnostics.Count == 0); return ParseFile(parseOptions, scriptParseOptions, content, file); } } private static SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) { var tree = SyntaxFactory.ParseSyntaxTree( content, file.IsScript ? scriptParseOptions : parseOptions, file.Path); // prepopulate line tables. // we will need line tables anyways and it is better to not wait until we are in emit // where things run sequentially. bool isHiddenDummy; tree.GetMappedLineSpanAndVisibility(default(TextSpan), out isHiddenDummy); return tree; } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output. /// 2) The path of the assembly/module file. /// 3) The path of the pdb file. /// /// When csc produces an executable, but the name of the resulting assembly /// is not specified using the "/out" switch, the name is taken from the name /// of the file (note: file, not class) containing the assembly entrypoint /// (as determined by binding and the "/main" switch). /// /// For example, if the command is "csc /target:exe a.cs b.cs" and b.cs contains the /// entrypoint, then csc will produce "b.exe" and "b.pdb" in the output directory, /// with assembly name "b" and module name "b.exe" embedded in the file. /// </summary> protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { if (Arguments.OutputFileName is object) { return Arguments.OutputFileName; } Debug.Assert(Arguments.CompilationOptions.OutputKind.IsApplication()); var comp = (CSharpCompilation)compilation; Symbol? entryPoint = comp.ScriptClass; if (entryPoint is null) { var method = comp.GetEntryPoint(cancellationToken); if (method is object) { entryPoint = method.PartialImplementationPart ?? method; } else { // no entrypoint found - an error will be reported and the compilation won't be emitted return "error"; } } string entryPointFileName = PathUtilities.GetFileName(entryPoint.Locations.First().SourceTree!.FilePath); return Path.ChangeExtension(entryPointFileName, ".exe"); } internal override bool SuppressDefaultResponseFile(IEnumerable<string> args) { return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); } /// <summary> /// Print compiler logo /// </summary> /// <param name="consoleOutput"></param> public override void PrintLogo(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()); consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, Culture)); consoleOutput.WriteLine(); } public override void PrintLangVersions(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LangVersions, Culture)); var defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); var latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); foreach (var v in (LanguageVersion[])Enum.GetValues(typeof(LanguageVersion))) { if (v == defaultVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (default)"); } else if (v == latestVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)"); } else { consoleOutput.WriteLine(v.ToDisplayString()); } } consoleOutput.WriteLine(); } internal override Type Type { get { // We do not use this.GetType() so that we don't break mock subtypes return typeof(CSharpCompiler); } } internal override string GetToolName() { return ErrorFacts.GetMessage(MessageID.IDS_ToolName, Culture); } /// <summary> /// Print Commandline help message (up to 80 English characters per line) /// </summary> /// <param name="consoleOutput"></param> public override void PrintHelp(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, Culture)); } protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) { return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); } protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { Arguments.ResolveAnalyzersFromArguments(LanguageNames.CSharp, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, out analyzers, out generators); } protected override void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics) { foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives( d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) { var path = (string?)directive.File.Value; if (path == null) { continue; } string? resolvedPath = resolver.ResolveReference(path, tree.FilePath); if (resolvedPath == null) { diagnostics.Add( MessageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, directive.File.GetLocation(), path, CSharpResources.CouldNotFindFile)); continue; } embeddedFiles.Add(resolvedPath); } } private protected override Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag diagnostics) { var driver = CSharpGeneratorDriver.Create(generators, additionalTexts, (CSharpParseOptions)parseOptions, analyzerConfigProvider); driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var generatorDiagnostics); diagnostics.AddRange(generatorDiagnostics); return compilationOut; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract class CSharpCompiler : CommonCompiler { internal const string ResponseFileName = "csc.rsp"; private readonly CommandLineDiagnosticFormatter _diagnosticFormatter; private readonly string? _tempDirectory; protected CSharpCompiler(CSharpCommandLineParser parser, string? responseFile, string[] args, BuildPaths buildPaths, string? additionalReferenceDirectories, IAnalyzerAssemblyLoader assemblyLoader) : base(parser, responseFile, args, buildPaths, additionalReferenceDirectories, assemblyLoader) { _diagnosticFormatter = new CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, Arguments.PrintFullPaths, Arguments.ShouldIncludeErrorEndLocation); _tempDirectory = buildPaths.TempDirectory; } public override DiagnosticFormatter DiagnosticFormatter { get { return _diagnosticFormatter; } } protected internal new CSharpCommandLineArguments Arguments { get { return (CSharpCommandLineArguments)base.Arguments; } } public override Compilation? CreateCompilation( TextWriter consoleOutput, TouchedFileLogger? touchedFilesLogger, ErrorLogger? errorLogger, ImmutableArray<AnalyzerConfigOptionsResult> analyzerConfigOptions, AnalyzerConfigOptionsResult globalConfigOptions) { var parseOptions = Arguments.ParseOptions; // We compute script parse options once so we don't have to do it repeatedly in // case there are many script files. var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); bool hadErrors = false; var sourceFiles = Arguments.SourceFiles; var trees = new SyntaxTree?[sourceFiles.Length]; var normalizedFilePaths = new string?[sourceFiles.Length]; var diagnosticBag = DiagnosticBag.GetInstance(); if (Arguments.CompilationOptions.ConcurrentBuild) { RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); }), CancellationToken.None); } else { for (int i = 0; i < sourceFiles.Length; i++) { //NOTE: order of trees is important!! trees[i] = ParseFile( parseOptions, scriptParseOptions, ref hadErrors, sourceFiles[i], diagnosticBag, out normalizedFilePaths[i]); } } // If errors had been reported in ParseFile, while trying to read files, then we should simply exit. if (ReportDiagnostics(diagnosticBag.ToReadOnlyAndFree(), consoleOutput, errorLogger, compilation: null)) { Debug.Assert(hadErrors); return null; } var diagnostics = new List<DiagnosticInfo>(); var uniqueFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < sourceFiles.Length; i++) { var normalizedFilePath = normalizedFilePaths[i]; Debug.Assert(normalizedFilePath != null); Debug.Assert(sourceFiles[i].IsInputRedirected || PathUtilities.IsAbsolute(normalizedFilePath)); if (!uniqueFilePaths.Add(normalizedFilePath)) { // warning CS2002: Source file '{0}' specified multiple times diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.WRN_FileAlreadyIncluded, Arguments.PrintFullPaths ? normalizedFilePath : _diagnosticFormatter.RelativizeNormalizedPath(normalizedFilePath))); trees[i] = null; } } if (Arguments.TouchedFilesPath != null) { Debug.Assert(touchedFilesLogger is object); foreach (var path in uniqueFilePaths) { touchedFilesLogger.AddRead(path); } } var assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default; var appConfigPath = this.Arguments.AppConfigPath; if (appConfigPath != null) { try { using (var appConfigStream = new FileStream(appConfigPath, FileMode.Open, FileAccess.Read)) { assemblyIdentityComparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream); } if (touchedFilesLogger != null) { touchedFilesLogger.AddRead(appConfigPath); } } catch (Exception ex) { diagnostics.Add(new DiagnosticInfo(MessageProvider, (int)ErrorCode.ERR_CantReadConfigFile, appConfigPath, ex.Message)); } } var xmlFileResolver = new LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger); var sourceFileResolver = new LoggingSourceFileResolver(ImmutableArray<string>.Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger); MetadataReferenceResolver referenceDirectiveResolver; var resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, out referenceDirectiveResolver); if (ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation: null)) { return null; } var loggingFileSystem = new LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory); var optionsProvider = new CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalConfigOptions); return CSharpCompilation.Create( Arguments.CompilationName, trees.WhereNotNull(), resolvedReferences, Arguments.CompilationOptions .WithMetadataReferenceResolver(referenceDirectiveResolver) .WithAssemblyIdentityComparer(assemblyIdentityComparer) .WithXmlReferenceResolver(xmlFileResolver) .WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)) .WithSourceReferenceResolver(sourceFileResolver) .WithSyntaxTreeOptionsProvider(optionsProvider)); } private SyntaxTree? ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, ref bool addedDiagnostics, CommandLineSourceFile file, DiagnosticBag diagnostics, out string? normalizedFilePath) { var fileDiagnostics = new List<DiagnosticInfo>(); var content = TryReadFileContent(file, fileDiagnostics, out normalizedFilePath); if (content == null) { foreach (var info in fileDiagnostics) { diagnostics.Add(MessageProvider.CreateDiagnostic(info)); } fileDiagnostics.Clear(); addedDiagnostics = true; return null; } else { Debug.Assert(fileDiagnostics.Count == 0); return ParseFile(parseOptions, scriptParseOptions, content, file); } } private static SyntaxTree ParseFile( CSharpParseOptions parseOptions, CSharpParseOptions scriptParseOptions, SourceText content, CommandLineSourceFile file) { var tree = SyntaxFactory.ParseSyntaxTree( content, file.IsScript ? scriptParseOptions : parseOptions, file.Path); // prepopulate line tables. // we will need line tables anyways and it is better to not wait until we are in emit // where things run sequentially. bool isHiddenDummy; tree.GetMappedLineSpanAndVisibility(default(TextSpan), out isHiddenDummy); return tree; } /// <summary> /// Given a compilation and a destination directory, determine three names: /// 1) The name with which the assembly should be output. /// 2) The path of the assembly/module file. /// 3) The path of the pdb file. /// /// When csc produces an executable, but the name of the resulting assembly /// is not specified using the "/out" switch, the name is taken from the name /// of the file (note: file, not class) containing the assembly entrypoint /// (as determined by binding and the "/main" switch). /// /// For example, if the command is "csc /target:exe a.cs b.cs" and b.cs contains the /// entrypoint, then csc will produce "b.exe" and "b.pdb" in the output directory, /// with assembly name "b" and module name "b.exe" embedded in the file. /// </summary> protected override string GetOutputFileName(Compilation compilation, CancellationToken cancellationToken) { if (Arguments.OutputFileName is object) { return Arguments.OutputFileName; } Debug.Assert(Arguments.CompilationOptions.OutputKind.IsApplication()); var comp = (CSharpCompilation)compilation; Symbol? entryPoint = comp.ScriptClass; if (entryPoint is null) { var method = comp.GetEntryPoint(cancellationToken); if (method is object) { entryPoint = method.PartialImplementationPart ?? method; } else { // no entrypoint found - an error will be reported and the compilation won't be emitted return "error"; } } string entryPointFileName = PathUtilities.GetFileName(entryPoint.Locations.First().SourceTree!.FilePath); return Path.ChangeExtension(entryPointFileName, ".exe"); } internal override bool SuppressDefaultResponseFile(IEnumerable<string> args) { return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); } /// <summary> /// Print compiler logo /// </summary> /// <param name="consoleOutput"></param> public override void PrintLogo(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()); consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LogoLine2, Culture)); consoleOutput.WriteLine(); } public override void PrintLangVersions(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_LangVersions, Culture)); var defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); var latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion(); foreach (var v in (LanguageVersion[])Enum.GetValues(typeof(LanguageVersion))) { if (v == defaultVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (default)"); } else if (v == latestVersion) { consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)"); } else { consoleOutput.WriteLine(v.ToDisplayString()); } } consoleOutput.WriteLine(); } internal override Type Type { get { // We do not use this.GetType() so that we don't break mock subtypes return typeof(CSharpCompiler); } } internal override string GetToolName() { return ErrorFacts.GetMessage(MessageID.IDS_ToolName, Culture); } /// <summary> /// Print Commandline help message (up to 80 English characters per line) /// </summary> /// <param name="consoleOutput"></param> public override void PrintHelp(TextWriter consoleOutput) { consoleOutput.WriteLine(ErrorFacts.GetMessage(MessageID.IDS_CSCHelp, Culture)); } protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code) { return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code); } protected override void ResolveAnalyzersFromArguments( List<DiagnosticInfo> diagnostics, CommonMessageProvider messageProvider, bool skipAnalyzers, out ImmutableArray<DiagnosticAnalyzer> analyzers, out ImmutableArray<ISourceGenerator> generators) { Arguments.ResolveAnalyzersFromArguments(LanguageNames.CSharp, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, out analyzers, out generators); } protected override void ResolveEmbeddedFilesFromExternalSourceDirectives( SyntaxTree tree, SourceReferenceResolver resolver, OrderedSet<string> embeddedFiles, DiagnosticBag diagnostics) { foreach (LineDirectiveTriviaSyntax directive in tree.GetRoot().GetDirectives( d => d.IsActive && !d.HasErrors && d.Kind() == SyntaxKind.LineDirectiveTrivia)) { var path = (string?)directive.File.Value; if (path == null) { continue; } string? resolvedPath = resolver.ResolveReference(path, tree.FilePath); if (resolvedPath == null) { diagnostics.Add( MessageProvider.CreateDiagnostic( (int)ErrorCode.ERR_NoSourceFile, directive.File.GetLocation(), path, CSharpResources.CouldNotFindFile)); continue; } embeddedFiles.Add(resolvedPath); } } private protected override Compilation RunGenerators(Compilation input, ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider analyzerConfigProvider, ImmutableArray<AdditionalText> additionalTexts, DiagnosticBag diagnostics) { var driver = CSharpGeneratorDriver.Create(generators, additionalTexts, (CSharpParseOptions)parseOptions, analyzerConfigProvider); driver.RunGeneratorsAndUpdateCompilation(input, out var compilationOut, out var generatorDiagnostics); diagnostics.AddRange(generatorDiagnostics); return compilationOut; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Sort.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Sort.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { public static IEnumerable<object[]> ValidCollectionSizes_GreaterThanOne() { yield return new object[] { 2 }; yield return new object[] { 20 }; } #region Sort [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> comparer = Comparer<T>.Default; list.Sort(); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> comparer = Comparer<T>.Default; list.Sort(); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(IComparer) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_IComparer_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_IComparer_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> comparer = GetIComparer(); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(Comparison) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_Comparison_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> iComparer = GetIComparer(); Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); }); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(iComparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_Comparison_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> iComparer = GetIComparer(); Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); }); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(iComparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(int, int, IComparer<T>) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_intintIComparer_WithoutDuplicates(int count) { SegmentedList<T> unsortedList = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); for (int startIndex = 0; startIndex < count - 2; startIndex++) for (int sortCount = 1; sortCount < count - startIndex; sortCount++) { SegmentedList<T> list = new SegmentedList<T>(unsortedList); list.Sort(startIndex, sortCount + 1, comparer); for (int i = startIndex; i < sortCount; i++) Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 0); } } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_intintIComparer_WithDuplicates(int count) { SegmentedList<T> unsortedList = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); unsortedList.Add(unsortedList[0]); for (int startIndex = 0; startIndex < count - 2; startIndex++) for (int sortCount = 2; sortCount < count - startIndex; sortCount++) { SegmentedList<T> list = new SegmentedList<T>(unsortedList); list.Sort(startIndex, sortCount + 1, comparer); for (int i = startIndex; i < sortCount; i++) Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 1); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Sort_intintIComparer_NegativeRange_ThrowsArgumentOutOfRangeException(int count) { SegmentedList<T> list = GenericListFactory(count); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(-2, 0), Tuple.Create(int.MinValue, 0), Tuple.Create(0 ,-1), Tuple.Create(0 ,-2), Tuple.Create(0 , int.MinValue), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer())); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Sort_intintIComparer_InvalidRange_ThrowsArgumentException(int count) { SegmentedList<T> list = GenericListFactory(count); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(count, 1), Tuple.Create(count + 1, 0), Tuple.Create(int.MaxValue, 0), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentException>(null, () => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer())); }); } #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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Sort.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { public static IEnumerable<object[]> ValidCollectionSizes_GreaterThanOne() { yield return new object[] { 2 }; yield return new object[] { 20 }; } #region Sort [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> comparer = Comparer<T>.Default; list.Sort(); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> comparer = Comparer<T>.Default; list.Sort(); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(IComparer) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_IComparer_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_IComparer_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> comparer = GetIComparer(); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(Comparison) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_Comparison_WithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); IComparer<T> iComparer = GetIComparer(); Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); }); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(iComparer.Compare(list[i], list[i + 1]) < 0); }); } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_Comparison_WithDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); IComparer<T> iComparer = GetIComparer(); Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); }); list.Sort(comparer); Assert.All(Enumerable.Range(0, count - 2), i => { Assert.True(iComparer.Compare(list[i], list[i + 1]) <= 0); }); } #endregion #region Sort(int, int, IComparer<T>) [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_intintIComparer_WithoutDuplicates(int count) { SegmentedList<T> unsortedList = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); for (int startIndex = 0; startIndex < count - 2; startIndex++) for (int sortCount = 1; sortCount < count - startIndex; sortCount++) { SegmentedList<T> list = new SegmentedList<T>(unsortedList); list.Sort(startIndex, sortCount + 1, comparer); for (int i = startIndex; i < sortCount; i++) Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 0); } } [Theory] [MemberData(nameof(ValidCollectionSizes_GreaterThanOne))] public void Sort_intintIComparer_WithDuplicates(int count) { SegmentedList<T> unsortedList = GenericListFactory(count); IComparer<T> comparer = GetIComparer(); unsortedList.Add(unsortedList[0]); for (int startIndex = 0; startIndex < count - 2; startIndex++) for (int sortCount = 2; sortCount < count - startIndex; sortCount++) { SegmentedList<T> list = new SegmentedList<T>(unsortedList); list.Sort(startIndex, sortCount + 1, comparer); for (int i = startIndex; i < sortCount; i++) Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 1); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Sort_intintIComparer_NegativeRange_ThrowsArgumentOutOfRangeException(int count) { SegmentedList<T> list = GenericListFactory(count); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(-1,-1), Tuple.Create(-1, 0), Tuple.Create(-1, 1), Tuple.Create(-1, 2), Tuple.Create(-2, 0), Tuple.Create(int.MinValue, 0), Tuple.Create(0 ,-1), Tuple.Create(0 ,-2), Tuple.Create(0 , int.MinValue), Tuple.Create(1 ,-1), Tuple.Create(2 ,-1), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer())); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Sort_intintIComparer_InvalidRange_ThrowsArgumentException(int count) { SegmentedList<T> list = GenericListFactory(count); Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[] { Tuple.Create(count, 1), Tuple.Create(count + 1, 0), Tuple.Create(int.MaxValue, 0), }; Assert.All(InvalidParameters, invalidSet => { Assert.Throws<ArgumentException>(null, () => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer())); }); } #endregion } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/Diagnostic/LocalizableResourceString.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Resources; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A localizable resource string that may possibly be formatted differently depending on culture. /// </summary> public sealed class LocalizableResourceString : LocalizableString, IObjectWritable { private readonly string _nameOfLocalizableResource; private readonly ResourceManager _resourceManager; private readonly Type _resourceSource; private readonly string[] _formatArguments; static LocalizableResourceString() { ObjectBinder.RegisterTypeReader(typeof(LocalizableResourceString), reader => new LocalizableResourceString(reader)); } /// <summary> /// Creates a localizable resource string with no formatting arguments. /// </summary> /// <param name="nameOfLocalizableResource">nameof the resource that needs to be localized.</param> /// <param name="resourceManager"><see cref="ResourceManager"/> for the calling assembly.</param> /// <param name="resourceSource">Type handling assembly's resource management. Typically, this is the static class generated for the resources file from which resources are accessed.</param> public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource) : this(nameOfLocalizableResource, resourceManager, resourceSource, Array.Empty<string>()) { } /// <summary> /// Creates a localizable resource string that may possibly be formatted differently depending on culture. /// </summary> /// <param name="nameOfLocalizableResource">nameof the resource that needs to be localized.</param> /// <param name="resourceManager"><see cref="ResourceManager"/> for the calling assembly.</param> /// <param name="resourceSource">Type handling assembly's resource management. Typically, this is the static class generated for the resources file from which resources are accessed.</param> /// <param name="formatArguments">Optional arguments for formatting the localizable resource string.</param> public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource, params string[] formatArguments) { if (nameOfLocalizableResource == null) { throw new ArgumentNullException(nameof(nameOfLocalizableResource)); } if (resourceManager == null) { throw new ArgumentNullException(nameof(resourceManager)); } if (resourceSource == null) { throw new ArgumentNullException(nameof(resourceSource)); } if (formatArguments == null) { throw new ArgumentNullException(nameof(formatArguments)); } _resourceManager = resourceManager; _nameOfLocalizableResource = nameOfLocalizableResource; _resourceSource = resourceSource; _formatArguments = formatArguments; } private LocalizableResourceString(ObjectReader reader) { _resourceSource = reader.ReadType(); _nameOfLocalizableResource = reader.ReadString(); _resourceManager = new ResourceManager(_resourceSource); var length = reader.ReadInt32(); if (length == 0) { _formatArguments = Array.Empty<string>(); } else { var argumentsBuilder = ArrayBuilder<string>.GetInstance(length); for (int i = 0; i < length; i++) { argumentsBuilder.Add(reader.ReadString()); } _formatArguments = argumentsBuilder.ToArrayAndFree(); } } bool IObjectWritable.ShouldReuseInSerialization => false; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteType(_resourceSource); writer.WriteString(_nameOfLocalizableResource); var length = _formatArguments.Length; writer.WriteInt32(length); for (int i = 0; i < length; i++) { writer.WriteString(_formatArguments[i]); } } protected override string GetText(IFormatProvider? formatProvider) { var culture = formatProvider as CultureInfo ?? CultureInfo.CurrentUICulture; var resourceString = _resourceManager.GetString(_nameOfLocalizableResource, culture); return resourceString != null ? (_formatArguments.Length > 0 ? string.Format(resourceString, _formatArguments) : resourceString) : string.Empty; } protected override bool AreEqual(object? other) { var otherResourceString = other as LocalizableResourceString; return otherResourceString != null && _nameOfLocalizableResource == otherResourceString._nameOfLocalizableResource && _resourceManager == otherResourceString._resourceManager && _resourceSource == otherResourceString._resourceSource && _formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b); } protected override int GetHash() { return Hash.Combine(_nameOfLocalizableResource.GetHashCode(), Hash.Combine(_resourceManager.GetHashCode(), Hash.Combine(_resourceSource.GetHashCode(), Hash.CombineValues(_formatArguments)))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.Linq; using System.Resources; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A localizable resource string that may possibly be formatted differently depending on culture. /// </summary> public sealed class LocalizableResourceString : LocalizableString, IObjectWritable { private readonly string _nameOfLocalizableResource; private readonly ResourceManager _resourceManager; private readonly Type _resourceSource; private readonly string[] _formatArguments; static LocalizableResourceString() { ObjectBinder.RegisterTypeReader(typeof(LocalizableResourceString), reader => new LocalizableResourceString(reader)); } /// <summary> /// Creates a localizable resource string with no formatting arguments. /// </summary> /// <param name="nameOfLocalizableResource">nameof the resource that needs to be localized.</param> /// <param name="resourceManager"><see cref="ResourceManager"/> for the calling assembly.</param> /// <param name="resourceSource">Type handling assembly's resource management. Typically, this is the static class generated for the resources file from which resources are accessed.</param> public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource) : this(nameOfLocalizableResource, resourceManager, resourceSource, Array.Empty<string>()) { } /// <summary> /// Creates a localizable resource string that may possibly be formatted differently depending on culture. /// </summary> /// <param name="nameOfLocalizableResource">nameof the resource that needs to be localized.</param> /// <param name="resourceManager"><see cref="ResourceManager"/> for the calling assembly.</param> /// <param name="resourceSource">Type handling assembly's resource management. Typically, this is the static class generated for the resources file from which resources are accessed.</param> /// <param name="formatArguments">Optional arguments for formatting the localizable resource string.</param> public LocalizableResourceString(string nameOfLocalizableResource, ResourceManager resourceManager, Type resourceSource, params string[] formatArguments) { if (nameOfLocalizableResource == null) { throw new ArgumentNullException(nameof(nameOfLocalizableResource)); } if (resourceManager == null) { throw new ArgumentNullException(nameof(resourceManager)); } if (resourceSource == null) { throw new ArgumentNullException(nameof(resourceSource)); } if (formatArguments == null) { throw new ArgumentNullException(nameof(formatArguments)); } _resourceManager = resourceManager; _nameOfLocalizableResource = nameOfLocalizableResource; _resourceSource = resourceSource; _formatArguments = formatArguments; } private LocalizableResourceString(ObjectReader reader) { _resourceSource = reader.ReadType(); _nameOfLocalizableResource = reader.ReadString(); _resourceManager = new ResourceManager(_resourceSource); var length = reader.ReadInt32(); if (length == 0) { _formatArguments = Array.Empty<string>(); } else { var argumentsBuilder = ArrayBuilder<string>.GetInstance(length); for (int i = 0; i < length; i++) { argumentsBuilder.Add(reader.ReadString()); } _formatArguments = argumentsBuilder.ToArrayAndFree(); } } bool IObjectWritable.ShouldReuseInSerialization => false; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteType(_resourceSource); writer.WriteString(_nameOfLocalizableResource); var length = _formatArguments.Length; writer.WriteInt32(length); for (int i = 0; i < length; i++) { writer.WriteString(_formatArguments[i]); } } protected override string GetText(IFormatProvider? formatProvider) { var culture = formatProvider as CultureInfo ?? CultureInfo.CurrentUICulture; var resourceString = _resourceManager.GetString(_nameOfLocalizableResource, culture); return resourceString != null ? (_formatArguments.Length > 0 ? string.Format(resourceString, _formatArguments) : resourceString) : string.Empty; } protected override bool AreEqual(object? other) { var otherResourceString = other as LocalizableResourceString; return otherResourceString != null && _nameOfLocalizableResource == otherResourceString._nameOfLocalizableResource && _resourceManager == otherResourceString._resourceManager && _resourceSource == otherResourceString._resourceSource && _formatArguments.SequenceEqual(otherResourceString._formatArguments, (a, b) => a == b); } protected override int GetHash() { return Hash.Combine(_nameOfLocalizableResource.GetHashCode(), Hash.Combine(_resourceManager.GetHashCode(), Hash.Combine(_resourceSource.GetHashCode(), Hash.CombineValues(_formatArguments)))); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Binder/WithExternAliasesBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder that brings extern aliases into the scope and deals with looking up names in them. /// </summary> internal abstract class WithExternAliasesBinder : Binder { internal WithExternAliasesBinder(Binder next) : base(next) { } internal abstract override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); LookupSymbolInAliases( ImmutableDictionary<string, AliasAndUsingDirective>.Empty, this.ExternAliases, originalBinder, result, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { // If we are looking only for labels we do not need to search through the imports. if ((options & LookupOptions.LabelsOnly) == 0) { AddLookupSymbolsInfoInAliases( ImmutableDictionary<string, AliasAndUsingDirective>.Empty, this.ExternAliases, result, options, originalBinder); } } protected sealed override SourceLocalSymbol? LookupLocal(SyntaxToken nameToken) { return null; } protected sealed override LocalFunctionSymbol? LookupLocalFunction(SyntaxToken nameToken) { return null; } internal sealed override uint LocalScopeDepth => Binder.ExternalScope; internal static WithExternAliasesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) { return new FromSyntax(declaringSymbol, declarationSyntax, next); } internal static WithExternAliasesBinder Create(ImmutableArray<AliasAndExternAliasDirective> externAliases, Binder next) { return new FromSymbols(externAliases, next); } private sealed class FromSyntax : WithExternAliasesBinder { private readonly SourceNamespaceSymbol _declaringSymbol; private readonly CSharpSyntaxNode _declarationSyntax; private ImmutableArray<AliasAndExternAliasDirective> _lazyExternAliases; internal FromSyntax(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) : base(next) { Debug.Assert(declarationSyntax.Kind() is SyntaxKind.CompilationUnit or SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration); _declaringSymbol = declaringSymbol; _declarationSyntax = declarationSyntax; } internal override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { if (_lazyExternAliases.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyExternAliases, _declaringSymbol.GetExternAliases(_declarationSyntax)); } return _lazyExternAliases; } } } private sealed class FromSymbols : WithExternAliasesBinder { private readonly ImmutableArray<AliasAndExternAliasDirective> _externAliases; internal FromSymbols(ImmutableArray<AliasAndExternAliasDirective> externAliases, Binder next) : base(next) { Debug.Assert(!externAliases.IsDefault); _externAliases = externAliases; } internal override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return _externAliases; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder that brings extern aliases into the scope and deals with looking up names in them. /// </summary> internal abstract class WithExternAliasesBinder : Binder { internal WithExternAliasesBinder(Binder next) : base(next) { } internal abstract override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); LookupSymbolInAliases( ImmutableDictionary<string, AliasAndUsingDirective>.Empty, this.ExternAliases, originalBinder, result, name, arity, basesBeingResolved, options, diagnose, ref useSiteInfo); } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { // If we are looking only for labels we do not need to search through the imports. if ((options & LookupOptions.LabelsOnly) == 0) { AddLookupSymbolsInfoInAliases( ImmutableDictionary<string, AliasAndUsingDirective>.Empty, this.ExternAliases, result, options, originalBinder); } } protected sealed override SourceLocalSymbol? LookupLocal(SyntaxToken nameToken) { return null; } protected sealed override LocalFunctionSymbol? LookupLocalFunction(SyntaxToken nameToken) { return null; } internal sealed override uint LocalScopeDepth => Binder.ExternalScope; internal static WithExternAliasesBinder Create(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) { return new FromSyntax(declaringSymbol, declarationSyntax, next); } internal static WithExternAliasesBinder Create(ImmutableArray<AliasAndExternAliasDirective> externAliases, Binder next) { return new FromSymbols(externAliases, next); } private sealed class FromSyntax : WithExternAliasesBinder { private readonly SourceNamespaceSymbol _declaringSymbol; private readonly CSharpSyntaxNode _declarationSyntax; private ImmutableArray<AliasAndExternAliasDirective> _lazyExternAliases; internal FromSyntax(SourceNamespaceSymbol declaringSymbol, CSharpSyntaxNode declarationSyntax, Binder next) : base(next) { Debug.Assert(declarationSyntax.Kind() is SyntaxKind.CompilationUnit or SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration); _declaringSymbol = declaringSymbol; _declarationSyntax = declarationSyntax; } internal override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { if (_lazyExternAliases.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyExternAliases, _declaringSymbol.GetExternAliases(_declarationSyntax)); } return _lazyExternAliases; } } } private sealed class FromSymbols : WithExternAliasesBinder { private readonly ImmutableArray<AliasAndExternAliasDirective> _externAliases; internal FromSymbols(ImmutableArray<AliasAndExternAliasDirective> externAliases, Binder next) : base(next) { Debug.Assert(!externAliases.IsDefault); _externAliases = externAliases; } internal override ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return _externAliases; } } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/Core/Portable/Structure/Syntax/BlockSpanCollector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Shared.Collections; namespace Microsoft.CodeAnalysis.Structure { internal class BlockSpanCollector { private readonly BlockStructureOptionProvider _optionProvider; private readonly ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> _nodeProviderMap; private readonly ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> _triviaProviderMap; private readonly CancellationToken _cancellationToken; private BlockSpanCollector( BlockStructureOptionProvider optionProvider, ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap, ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap, CancellationToken cancellationToken) { _optionProvider = optionProvider; _nodeProviderMap = nodeOutlinerMap; _triviaProviderMap = triviaOutlinerMap; _cancellationToken = cancellationToken; } public static void CollectBlockSpans( SyntaxNode syntaxRoot, BlockStructureOptionProvider optionProvider, ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap, ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap, ref TemporaryArray<BlockSpan> spans, CancellationToken cancellationToken) { var collector = new BlockSpanCollector(optionProvider, nodeOutlinerMap, triviaOutlinerMap, cancellationToken); collector.Collect(syntaxRoot, ref spans); } private void Collect(SyntaxNode root, ref TemporaryArray<BlockSpan> spans) { _cancellationToken.ThrowIfCancellationRequested(); foreach (var nodeOrToken in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (nodeOrToken.IsNode) { GetBlockSpans(nodeOrToken.AsNode()!, ref spans); } else { GetBlockSpans(nodeOrToken.AsToken(), ref spans); } } } private void GetBlockSpans(SyntaxNode node, ref TemporaryArray<BlockSpan> spans) { if (_nodeProviderMap.TryGetValue(node.GetType(), out var providers)) { foreach (var provider in providers) { _cancellationToken.ThrowIfCancellationRequested(); provider.CollectBlockSpans(node, ref spans, _optionProvider, _cancellationToken); } } } private void GetBlockSpans(SyntaxToken token, ref TemporaryArray<BlockSpan> spans) { GetOutliningSpans(token.LeadingTrivia, ref spans); GetOutliningSpans(token.TrailingTrivia, ref spans); } private void GetOutliningSpans(SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans) { foreach (var trivia in triviaList) { _cancellationToken.ThrowIfCancellationRequested(); if (_triviaProviderMap.TryGetValue(trivia.RawKind, out var providers)) { foreach (var provider in providers) { _cancellationToken.ThrowIfCancellationRequested(); provider.CollectBlockSpans(trivia, ref spans, _optionProvider, _cancellationToken); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.Structure { internal class BlockSpanCollector { private readonly BlockStructureOptionProvider _optionProvider; private readonly ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> _nodeProviderMap; private readonly ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> _triviaProviderMap; private readonly CancellationToken _cancellationToken; private BlockSpanCollector( BlockStructureOptionProvider optionProvider, ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap, ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap, CancellationToken cancellationToken) { _optionProvider = optionProvider; _nodeProviderMap = nodeOutlinerMap; _triviaProviderMap = triviaOutlinerMap; _cancellationToken = cancellationToken; } public static void CollectBlockSpans( SyntaxNode syntaxRoot, BlockStructureOptionProvider optionProvider, ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> nodeOutlinerMap, ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> triviaOutlinerMap, ref TemporaryArray<BlockSpan> spans, CancellationToken cancellationToken) { var collector = new BlockSpanCollector(optionProvider, nodeOutlinerMap, triviaOutlinerMap, cancellationToken); collector.Collect(syntaxRoot, ref spans); } private void Collect(SyntaxNode root, ref TemporaryArray<BlockSpan> spans) { _cancellationToken.ThrowIfCancellationRequested(); foreach (var nodeOrToken in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (nodeOrToken.IsNode) { GetBlockSpans(nodeOrToken.AsNode()!, ref spans); } else { GetBlockSpans(nodeOrToken.AsToken(), ref spans); } } } private void GetBlockSpans(SyntaxNode node, ref TemporaryArray<BlockSpan> spans) { if (_nodeProviderMap.TryGetValue(node.GetType(), out var providers)) { foreach (var provider in providers) { _cancellationToken.ThrowIfCancellationRequested(); provider.CollectBlockSpans(node, ref spans, _optionProvider, _cancellationToken); } } } private void GetBlockSpans(SyntaxToken token, ref TemporaryArray<BlockSpan> spans) { GetOutliningSpans(token.LeadingTrivia, ref spans); GetOutliningSpans(token.TrailingTrivia, ref spans); } private void GetOutliningSpans(SyntaxTriviaList triviaList, ref TemporaryArray<BlockSpan> spans) { foreach (var trivia in triviaList) { _cancellationToken.ThrowIfCancellationRequested(); if (_triviaProviderMap.TryGetValue(trivia.RawKind, out var providers)) { foreach (var provider in providers) { _cancellationToken.ThrowIfCancellationRequested(); provider.CollectBlockSpans(trivia, ref spans, _optionProvider, _cancellationToken); } } } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/LanguageServer/Protocol/Handler/DocumentChanges/DidOpenHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDidOpenName)] internal class DidOpenHandler : AbstractStatelessRequestHandler<LSP.DidOpenTextDocumentParams, object?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DidOpenHandler() { } public override string Method => LSP.Methods.TextDocumentDidOpenName; public override bool MutatesSolutionState => true; public override bool RequiresLSPSolution => false; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidOpenTextDocumentParams request) => new() { Uri = request.TextDocument.Uri }; public override Task<object?> HandleRequestAsync(LSP.DidOpenTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { // GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri. context.TraceInformation($"didOpen for {request.TextDocument.Uri}"); // Add the document and ensure the text we have matches whats on the client var sourceText = SourceText.From(request.TextDocument.Text, System.Text.Encoding.UTF8); context.StartTracking(request.TextDocument.Uri, sourceText); return SpecializedTasks.Default<object>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.DocumentChanges { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(LSP.Methods.TextDocumentDidOpenName)] internal class DidOpenHandler : AbstractStatelessRequestHandler<LSP.DidOpenTextDocumentParams, object?> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DidOpenHandler() { } public override string Method => LSP.Methods.TextDocumentDidOpenName; public override bool MutatesSolutionState => true; public override bool RequiresLSPSolution => false; public override LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.DidOpenTextDocumentParams request) => new() { Uri = request.TextDocument.Uri }; public override Task<object?> HandleRequestAsync(LSP.DidOpenTextDocumentParams request, RequestContext context, CancellationToken cancellationToken) { // GetTextDocumentIdentifier returns null to avoid creating the solution, so the queue is not able to log the uri. context.TraceInformation($"didOpen for {request.TextDocument.Uri}"); // Add the document and ensure the text we have matches whats on the client var sourceText = SourceText.From(request.TextDocument.Text, System.Text.Encoding.UTF8); context.StartTracking(request.TextDocument.Uri, sourceText); return SpecializedTasks.Default<object>(); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/Core/Portable/RQName/Nodes/RQMemberParameterIndex.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMemberParameterIndex : RQNode { public readonly RQMember ContainingMember; public readonly int ParameterIndex; public RQMemberParameterIndex( RQMember containingMember, int parameterIndex) { ContainingMember = containingMember; ParameterIndex = parameterIndex; } protected override string RQKeyword { get { return RQNameStrings.MemberParamIndex; } } protected override void AppendChildren(List<SimpleTreeNode> childList) { childList.Add(ContainingMember.ToSimpleTree()); childList.Add(new SimpleLeafNode(ParameterIndex.ToString())); childList.Add(new SimpleLeafNode(RQNameStrings.NotPartial)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMemberParameterIndex : RQNode { public readonly RQMember ContainingMember; public readonly int ParameterIndex; public RQMemberParameterIndex( RQMember containingMember, int parameterIndex) { ContainingMember = containingMember; ParameterIndex = parameterIndex; } protected override string RQKeyword { get { return RQNameStrings.MemberParamIndex; } } protected override void AppendChildren(List<SimpleTreeNode> childList) { childList.Add(ContainingMember.ToSimpleTree()); childList.Add(new SimpleLeafNode(ParameterIndex.ToString())); childList.Add(new SimpleLeafNode(RQNameStrings.NotPartial)); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.UnavailableTypeParameterRemover.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { private class UnavailableTypeParameterRemover : SymbolVisitor<ITypeSymbol> { private readonly Compilation _compilation; private readonly ISet<string> _availableTypeParameterNames; public UnavailableTypeParameterRemover(Compilation compilation, ISet<string> availableTypeParameterNames) { _compilation = compilation; _availableTypeParameterNames = availableTypeParameterNames; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => symbol; public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): implement this return symbol; } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); if (arguments.SequenceEqual(symbol.TypeArguments)) { return symbol; } return symbol.ConstructedFrom.Construct(arguments.ToArray()); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var elementType = symbol.PointedAtType.Accept(this); if (elementType != null && elementType.Equals(symbol.PointedAtType)) { return symbol; } return _compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) { if (_availableTypeParameterNames.Contains(symbol.Name)) { return symbol; } return _compilation.ObjectType; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ITypeSymbolExtensions { private class UnavailableTypeParameterRemover : SymbolVisitor<ITypeSymbol> { private readonly Compilation _compilation; private readonly ISet<string> _availableTypeParameterNames; public UnavailableTypeParameterRemover(Compilation compilation, ISet<string> availableTypeParameterNames) { _compilation = compilation; _availableTypeParameterNames = availableTypeParameterNames; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => symbol; public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): implement this return symbol; } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray(); if (arguments.SequenceEqual(symbol.TypeArguments)) { return symbol; } return symbol.ConstructedFrom.Construct(arguments.ToArray()); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var elementType = symbol.PointedAtType.Accept(this); if (elementType != null && elementType.Equals(symbol.PointedAtType)) { return symbol; } return _compilation.CreatePointerTypeSymbol(elementType); } public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) { if (_availableTypeParameterNames.Contains(symbol.Name)) { return symbol; } return _compilation.ObjectType; } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.AbstractIntroduceVariableCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { internal abstract class AbstractIntroduceVariableCodeAction : CodeAction { private readonly bool _allOccurrences; private readonly bool _isConstant; private readonly bool _isLocal; private readonly bool _isQueryLocal; private readonly TExpressionSyntax _expression; private readonly SemanticDocument _semanticDocument; private readonly TService _service; internal AbstractIntroduceVariableCodeAction( TService service, SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal) { _service = service; _semanticDocument = document; _expression = expression; _allOccurrences = allOccurrences; _isConstant = isConstant; _isLocal = isLocal; _isQueryLocal = isQueryLocal; Title = CreateDisplayText(expression); } public override string Title { get; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var changedDocument = await GetChangedDocumentCoreAsync(cancellationToken).ConfigureAwait(false); return await Simplifier.ReduceAsync(changedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<Document> GetChangedDocumentCoreAsync(CancellationToken cancellationToken) { if (_isQueryLocal) { return await _service.IntroduceQueryLocalAsync(_semanticDocument, _expression, _allOccurrences, cancellationToken).ConfigureAwait(false); } else if (_isLocal) { return await _service.IntroduceLocalAsync(_semanticDocument, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false); } else { return await _service.IntroduceFieldAsync(_semanticDocument, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false); } } private string CreateDisplayText(TExpressionSyntax expression) { var singleLineExpression = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>().ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); return CreateDisplayText(nodeString); } // Indexed by: allOccurrences, isConstant, isLocal private static readonly string[,,] formatStrings = new string[2, 2, 2] { { { FeaturesResources.Introduce_field_for_0, FeaturesResources.Introduce_local_for_0 }, { FeaturesResources.Introduce_constant_for_0, FeaturesResources.Introduce_local_constant_for_0 } }, { { FeaturesResources.Introduce_field_for_all_occurrences_of_0, FeaturesResources.Introduce_local_for_all_occurrences_of_0 }, { FeaturesResources.Introduce_constant_for_all_occurrences_of_0, FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0 } } }; private string CreateDisplayText(string nodeString) { var formatString = _isQueryLocal ? _allOccurrences ? FeaturesResources.Introduce_query_variable_for_all_occurrences_of_0 : FeaturesResources.Introduce_query_variable_for_0 : formatStrings[_allOccurrences ? 1 : 0, _isConstant ? 1 : 0, _isLocal ? 1 : 0]; return string.Format(formatString, nodeString); } protected ITypeSymbol GetExpressionType( CancellationToken cancellationToken) { var semanticModel = _semanticDocument.SemanticModel; var typeInfo = semanticModel.GetTypeInfo(_expression, cancellationToken); return typeInfo.Type ?? typeInfo.ConvertedType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { internal abstract class AbstractIntroduceVariableCodeAction : CodeAction { private readonly bool _allOccurrences; private readonly bool _isConstant; private readonly bool _isLocal; private readonly bool _isQueryLocal; private readonly TExpressionSyntax _expression; private readonly SemanticDocument _semanticDocument; private readonly TService _service; internal AbstractIntroduceVariableCodeAction( TService service, SemanticDocument document, TExpressionSyntax expression, bool allOccurrences, bool isConstant, bool isLocal, bool isQueryLocal) { _service = service; _semanticDocument = document; _expression = expression; _allOccurrences = allOccurrences; _isConstant = isConstant; _isLocal = isLocal; _isQueryLocal = isQueryLocal; Title = CreateDisplayText(expression); } public override string Title { get; } protected override async Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken) { var changedDocument = await GetChangedDocumentCoreAsync(cancellationToken).ConfigureAwait(false); return await Simplifier.ReduceAsync(changedDocument, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<Document> GetChangedDocumentCoreAsync(CancellationToken cancellationToken) { if (_isQueryLocal) { return await _service.IntroduceQueryLocalAsync(_semanticDocument, _expression, _allOccurrences, cancellationToken).ConfigureAwait(false); } else if (_isLocal) { return await _service.IntroduceLocalAsync(_semanticDocument, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false); } else { return await _service.IntroduceFieldAsync(_semanticDocument, _expression, _allOccurrences, _isConstant, cancellationToken).ConfigureAwait(false); } } private string CreateDisplayText(TExpressionSyntax expression) { var singleLineExpression = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>().ConvertToSingleLine(expression); var nodeString = singleLineExpression.ToString(); return CreateDisplayText(nodeString); } // Indexed by: allOccurrences, isConstant, isLocal private static readonly string[,,] formatStrings = new string[2, 2, 2] { { { FeaturesResources.Introduce_field_for_0, FeaturesResources.Introduce_local_for_0 }, { FeaturesResources.Introduce_constant_for_0, FeaturesResources.Introduce_local_constant_for_0 } }, { { FeaturesResources.Introduce_field_for_all_occurrences_of_0, FeaturesResources.Introduce_local_for_all_occurrences_of_0 }, { FeaturesResources.Introduce_constant_for_all_occurrences_of_0, FeaturesResources.Introduce_local_constant_for_all_occurrences_of_0 } } }; private string CreateDisplayText(string nodeString) { var formatString = _isQueryLocal ? _allOccurrences ? FeaturesResources.Introduce_query_variable_for_all_occurrences_of_0 : FeaturesResources.Introduce_query_variable_for_0 : formatStrings[_allOccurrences ? 1 : 0, _isConstant ? 1 : 0, _isLocal ? 1 : 0]; return string.Format(formatString, nodeString); } protected ITypeSymbol GetExpressionType( CancellationToken cancellationToken) { var semanticModel = _semanticDocument.SemanticModel; var typeInfo = semanticModel.GetTypeInfo(_expression, cancellationToken); return typeInfo.Type ?? typeInfo.ConvertedType ?? semanticModel.Compilation.GetSpecialType(SpecialType.System_Object); } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Binder/Binder_Deconstruct.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts deconstruction-assignment syntax (AssignmentExpressionSyntax nodes with the left /// being a tuple expression or declaration expression) into a BoundDeconstructionAssignmentOperator (or bad node). /// The BoundDeconstructionAssignmentOperator will have: /// - a BoundTupleLiteral as its Left, /// - a BoundConversion as its Right, holding: /// - a tree of Conversion objects with Kind=Deconstruction, information about a Deconstruct method (optional) and /// an array of nested Conversions (like a tuple conversion), /// - a BoundExpression as its Operand. /// </summary> internal partial class Binder { internal BoundExpression BindDeconstruction(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, bool resultIsUsedOverride = false) { var left = node.Left; var right = node.Right; DeclarationExpressionSyntax? declaration = null; ExpressionSyntax? expression = null; var result = BindDeconstruction(node, left, right, diagnostics, ref declaration, ref expression, resultIsUsedOverride); if (declaration != null) { // only allowed at the top level, or in a for loop switch (node.Parent?.Kind()) { case null: case SyntaxKind.ExpressionStatement: if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } break; case SyntaxKind.ForStatement: if (((ForStatementSyntax)node.Parent).Initializers.Contains(node)) { if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } } else { Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); } break; default: Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); break; } } return result; } /// <summary> /// Bind a deconstruction assignment. /// </summary> /// <param name="deconstruction">The deconstruction operation</param> /// <param name="left">The left (tuple) operand</param> /// <param name="right">The right (deconstructable) operand</param> /// <param name="diagnostics">Where to report diagnostics</param> /// <param name="declaration">A variable set to the first variable declaration found in the left</param> /// <param name="expression">A variable set to the first expression in the left that isn't a declaration or discard</param> /// <param name="resultIsUsedOverride">The expression evaluator needs to bind deconstructions (both assignments and declarations) as expression-statements /// and still access the returned value</param> /// <param name="rightPlaceholder"></param> /// <returns></returns> internal BoundDeconstructionAssignmentOperator BindDeconstruction( CSharpSyntaxNode deconstruction, ExpressionSyntax left, ExpressionSyntax right, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression, bool resultIsUsedOverride = false, BoundDeconstructValuePlaceholder? rightPlaceholder = null) { DeconstructionVariable locals = BindDeconstructionVariables(left, diagnostics, ref declaration, ref expression); Debug.Assert(locals.NestedVariables is object); var deconstructionDiagnostics = new BindingDiagnosticBag(new DiagnosticBag(), diagnostics.DependenciesBag); BoundExpression boundRight = rightPlaceholder ?? BindValue(right, deconstructionDiagnostics, BindValueKind.RValue); boundRight = FixTupleLiteral(locals.NestedVariables, boundRight, deconstruction, deconstructionDiagnostics); boundRight = BindToNaturalType(boundRight, diagnostics); bool resultIsUsed = resultIsUsedOverride || IsDeconstructionResultUsed(left); var assignment = BindDeconstructionAssignment(deconstruction, left, boundRight, locals.NestedVariables, resultIsUsed, deconstructionDiagnostics); DeconstructionVariable.FreeDeconstructionVariables(locals.NestedVariables); diagnostics.AddRange(deconstructionDiagnostics.DiagnosticBag); return assignment; } private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment( CSharpSyntaxNode node, ExpressionSyntax left, BoundExpression boundRHS, ArrayBuilder<DeconstructionVariable> checkedVariables, bool resultIsUsed, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); uint rightEscape = GetValEscape(boundRHS, this.LocalScopeDepth); if ((object?)boundRHS.Type == null || boundRHS.Type.IsErrorType()) { // we could still not infer a type for the RHS FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var voidType = GetSpecialType(SpecialType.System_Void, diagnostics, node); var type = boundRHS.Type ?? voidType; return new BoundDeconstructionAssignmentOperator( node, DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true), new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: type, hasErrors: true), resultIsUsed, voidType, hasErrors: true); } Conversion conversion; bool hasErrors = !MakeDeconstructionConversion( boundRHS.Type, node, boundRHS.Syntax, diagnostics, checkedVariables, out conversion); if (conversion.Method != null) { CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics); } FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var lhsTuple = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: diagnostics.HasAnyErrors() || !resultIsUsed); Debug.Assert(hasErrors || lhsTuple.Type is object); TypeSymbol returnType = hasErrors ? CreateErrorType() : lhsTuple.Type!; uint leftEscape = GetBroadestValEscape(lhsTuple, this.LocalScopeDepth); boundRHS = ValidateEscape(boundRHS, leftEscape, isByRef: false, diagnostics: diagnostics); var boundConversion = new BoundConversion( boundRHS.Syntax, boundRHS, conversion, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: returnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; return new BoundDeconstructionAssignmentOperator(node, lhsTuple, boundConversion, resultIsUsed, returnType); } private static bool IsDeconstructionResultUsed(ExpressionSyntax left) { var parent = left.Parent; if (parent is null || parent.Kind() == SyntaxKind.ForEachVariableStatement) { return false; } Debug.Assert(parent.Kind() == SyntaxKind.SimpleAssignmentExpression); var grandParent = parent.Parent; if (grandParent is null) { return false; } switch (grandParent.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)grandParent).Expression != parent; case SyntaxKind.ForStatement: // Incrementors and Initializers don't have to produce a value var loop = (ForStatementSyntax)grandParent; return !loop.Incrementors.Contains(parent) && !loop.Initializers.Contains(parent); default: return true; } } /// <summary>When boundRHS is a tuple literal, fix it up by inferring its types.</summary> private BoundExpression FixTupleLiteral(ArrayBuilder<DeconstructionVariable> checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); if (boundRHS.Kind == BoundKind.TupleLiteral) { // Let's fix the literal up by figuring out its type // For declarations, that means merging type information from the LHS and RHS // For assignments, only the LHS side matters since it is necessarily typed // If we already have diagnostics at this point, it is not worth collecting likely duplicate diagnostics from making the merged type bool hadErrors = diagnostics.HasAnyErrors(); TypeSymbol? mergedTupleType = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, hadErrors ? null : diagnostics); if ((object?)mergedTupleType != null) { boundRHS = GenerateConversionForAssignment(mergedTupleType, boundRHS, diagnostics); } } else if ((object?)boundRHS.Type == null) { Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, boundRHS.Syntax); } return boundRHS; } /// <summary> /// Recursively builds a Conversion object with Kind=Deconstruction including information about any necessary /// Deconstruct method and any element-wise conversion. /// /// Note that the variables may either be plain or nested variables. /// The variables may be updated with inferred types if they didn't have types initially. /// Returns false if there was an error. /// </summary> private bool MakeDeconstructionConversion( TypeSymbol type, SyntaxNode syntax, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, ArrayBuilder<DeconstructionVariable> variables, out Conversion conversion) { Debug.Assert((object)type != null); ImmutableArray<TypeSymbol> tupleOrDeconstructedTypes; conversion = Conversion.Deconstruction; // Figure out the deconstruct method (if one is required) and determine the types we get from the RHS at this level var deconstructMethod = default(DeconstructMethodInfo); if (type.IsTupleType) { // tuple literal such as `(1, 2)`, `(null, null)`, `(x.P, y.M())` tupleOrDeconstructedTypes = type.TupleElementTypesWithAnnotations.SelectAsArray(TypeMap.AsTypeSymbol); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); if (variables.Count != tupleOrDeconstructedTypes.Length) { Error(diagnostics, ErrorCode.ERR_DeconstructWrongCardinality, syntax, tupleOrDeconstructedTypes.Length, variables.Count); return false; } } else { if (variables.Count < 2) { Error(diagnostics, ErrorCode.ERR_DeconstructTooFewElements, syntax); return false; } var inputPlaceholder = new BoundDeconstructValuePlaceholder(syntax, this.LocalScopeDepth, type); BoundExpression deconstructInvocation = MakeDeconstructInvocationExpression(variables.Count, inputPlaceholder, rightSyntax, diagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out _); if (deconstructInvocation.HasAnyErrors) { return false; } deconstructMethod = new DeconstructMethodInfo(deconstructInvocation, inputPlaceholder, outPlaceholders); tupleOrDeconstructedTypes = outPlaceholders.SelectAsArray(p => p.Type); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); } // Figure out whether those types will need conversions, including further deconstructions bool hasErrors = false; int count = variables.Count; var nestedConversions = ArrayBuilder<Conversion>.GetInstance(count); for (int i = 0; i < count; i++) { var variable = variables[i]; Conversion nestedConversion; if (variable.NestedVariables is object) { var elementSyntax = syntax.Kind() == SyntaxKind.TupleExpression ? ((TupleExpressionSyntax)syntax).Arguments[i] : syntax; hasErrors |= !MakeDeconstructionConversion(tupleOrDeconstructedTypes[i], elementSyntax, rightSyntax, diagnostics, variable.NestedVariables, out nestedConversion); } else { var single = variable.Single; Debug.Assert(single is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); nestedConversion = this.Conversions.ClassifyConversionFromType(tupleOrDeconstructedTypes[i], single.Type, ref useSiteInfo); diagnostics.Add(single.Syntax, useSiteInfo); if (!nestedConversion.IsImplicit) { hasErrors = true; GenerateImplicitConversionError(diagnostics, Compilation, single.Syntax, nestedConversion, tupleOrDeconstructedTypes[i], single.Type); } } nestedConversions.Add(nestedConversion); } conversion = new Conversion(ConversionKind.Deconstruction, deconstructMethod, nestedConversions.ToImmutableAndFree()); return !hasErrors; } /// <summary> /// Inform the variables about found types. /// </summary> private void SetInferredTypes(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<TypeSymbol> foundTypes, BindingDiagnosticBag diagnostics) { var matchCount = Math.Min(variables.Count, foundTypes.Length); for (int i = 0; i < matchCount; i++) { var variable = variables[i]; if (variable.Single is { } pending) { if ((object?)pending.Type != null) { continue; } variables[i] = new DeconstructionVariable(SetInferredType(pending, foundTypes[i], diagnostics), variable.Syntax); } } } private BoundExpression SetInferredType(BoundExpression expression, TypeSymbol type, BindingDiagnosticBag diagnostics) { switch (expression.Kind) { case BoundKind.DeconstructionVariablePendingInference: { var pending = (DeconstructionVariablePendingInference)expression; return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type), this, diagnostics); } case BoundKind.DiscardExpression: { var pending = (BoundDiscardExpression)expression; Debug.Assert((object?)pending.Type == null); return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)); } default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Find any deconstruction locals that are still pending inference and fail their inference. /// Set the safe-to-escape scope for all deconstruction locals. /// </summary> private void FailRemainingInferencesAndSetValEscape(ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, uint rhsValEscape) { int count = variables.Count; for (int i = 0; i < count; i++) { var variable = variables[i]; if (variable.NestedVariables is object) { FailRemainingInferencesAndSetValEscape(variable.NestedVariables, diagnostics, rhsValEscape); } else { Debug.Assert(variable.Single is object); switch (variable.Single.Kind) { case BoundKind.Local: var local = (BoundLocal)variable.Single; if (local.DeclarationKind != BoundLocalDeclarationKind.None) { ((SourceLocalSymbol)local.LocalSymbol).SetValEscape(rhsValEscape); } break; case BoundKind.DeconstructionVariablePendingInference: BoundExpression errorLocal = ((DeconstructionVariablePendingInference)variable.Single).FailInference(this, diagnostics); variables[i] = new DeconstructionVariable(errorLocal, errorLocal.Syntax); break; case BoundKind.DiscardExpression: var pending = (BoundDiscardExpression)variable.Single; if ((object?)pending.Type == null) { Error(diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, pending.Syntax, "_"); variables[i] = new DeconstructionVariable(pending.FailInference(this, diagnostics), pending.Syntax); } break; } // at this point we expect to have a type for every lvalue Debug.Assert((object?)variables[i].Single!.Type != null); } } } /// <summary> /// Holds the variables on the LHS of a deconstruction as a tree of bound expressions. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class DeconstructionVariable { internal readonly BoundExpression? Single; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal readonly CSharpSyntaxNode Syntax; internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax) { Single = variable; NestedVariables = null; Syntax = (CSharpSyntaxNode)syntax; } internal DeconstructionVariable(ArrayBuilder<DeconstructionVariable> variables, SyntaxNode syntax) { Single = null; NestedVariables = variables; Syntax = (CSharpSyntaxNode)syntax; } internal static void FreeDeconstructionVariables(ArrayBuilder<DeconstructionVariable> variables) { variables.FreeAll(v => v.NestedVariables); } private string GetDebuggerDisplay() { if (Single != null) { return Single.GetDebuggerDisplay(); } Debug.Assert(NestedVariables is object); return $"Nested variables ({NestedVariables.Count})"; } } /// <summary> /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS. /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type. /// Returns null if a merged tuple type could not be fabricated. /// </summary> private TypeSymbol? MakeMergedTupleType(ArrayBuilder<DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, BindingDiagnosticBag? diagnostics) { int leftLength = lhsVariables.Count; int rightLength = rhsLiteral.Arguments.Length; var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(leftLength); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(leftLength); for (int i = 0; i < rightLength; i++) { BoundExpression element = rhsLiteral.Arguments[i]; TypeSymbol? mergedType = element.Type; if (i < leftLength) { var variable = lhsVariables[i]; if (variable.NestedVariables is object) { if (element.Kind == BoundKind.TupleLiteral) { // (variables) on the left and (elements) on the right mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, diagnostics); } else if ((object?)mergedType == null && diagnostics is object) { // (variables) on the left and null on the right Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } else { Debug.Assert(variable.Single is object); if ((object?)variable.Single.Type != null) { // typed-variable on the left mergedType = variable.Single.Type; } } } else { if ((object?)mergedType == null && diagnostics is object) { // a typeless element on the right, matching no variable on the left Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(mergedType)); locationsBuilder.Add(element.Syntax.Location); } if (typesWithAnnotationsBuilder.Any(t => !t.HasType)) { typesWithAnnotationsBuilder.Free(); locationsBuilder.Free(); return null; } // The tuple created here is not identical to the one created by // DeconstructionVariablesAsTuple. It represents a smaller // tree of types used for figuring out natural types in tuple literal. return NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: typesWithAnnotationsBuilder.ToImmutableAndFree(), elementLocations: locationsBuilder.ToImmutableAndFree(), elementNames: default(ImmutableArray<string?>), compilation: Compilation, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: default(ImmutableArray<bool>), syntax: syntax); } private BoundTupleExpression DeconstructionVariablesAsTuple(CSharpSyntaxNode syntax, ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, bool ignoreDiagnosticsFromTuple) { int count = variables.Count; var valuesBuilder = ArrayBuilder<BoundExpression>.GetInstance(count); var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(count); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(count); var namesBuilder = ArrayBuilder<string?>.GetInstance(count); foreach (var variable in variables) { BoundExpression value; if (variable.NestedVariables is object) { value = DeconstructionVariablesAsTuple(variable.Syntax, variable.NestedVariables, diagnostics, ignoreDiagnosticsFromTuple); namesBuilder.Add(null); } else { Debug.Assert(variable.Single is object); value = variable.Single; namesBuilder.Add(ExtractDeconstructResultElementName(value)); } valuesBuilder.Add(value); typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(value.Type)); locationsBuilder.Add(variable.Syntax.Location); } ImmutableArray<BoundExpression> arguments = valuesBuilder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string?> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); var type = NamedTypeSymbol.CreateTuple( syntax.Location, typesWithAnnotationsBuilder.ToImmutableAndFree(), locationsBuilder.ToImmutableAndFree(), tupleNames, this.Compilation, shouldCheckConstraints: !ignoreDiagnosticsFromTuple, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default, syntax: syntax, diagnostics: ignoreDiagnosticsFromTuple ? null : diagnostics); return (BoundTupleExpression)BindToNaturalType(new BoundTupleLiteral(syntax, arguments, tupleNames, inferredPositions, type), diagnostics); } /// <summary>Extract inferred name from a single deconstruction variable.</summary> private static string? ExtractDeconstructResultElementName(BoundExpression expression) { if (expression.Kind == BoundKind.DiscardExpression) { return null; } return InferTupleElementName(expression.Syntax); } /// <summary> /// Find the Deconstruct method for the expression on the right, that will fit the number of assignable variables on the left. /// Returns an invocation expression if the Deconstruct method is found. /// If so, it outputs placeholders that were coerced to the output types of the resolved Deconstruct method. /// The overload resolution is similar to writing <c>receiver.Deconstruct(out var x1, out var x2, ...)</c>. /// </summary> private BoundExpression MakeDeconstructInvocationExpression( int numCheckedVariables, BoundExpression receiver, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyApplicableCandidates) { anyApplicableCandidates = false; var receiverSyntax = (CSharpSyntaxNode)receiver.Syntax; if (receiver.Type?.IsDynamic() ?? false) { Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, rightSyntax); outPlaceholders = default(ImmutableArray<BoundDeconstructValuePlaceholder>); return BadExpression(receiverSyntax, receiver); } receiver = BindToNaturalType(receiver, diagnostics); var analyzedArguments = AnalyzedArguments.GetInstance(); var outVars = ArrayBuilder<OutDeconstructVarPendingInference>.GetInstance(numCheckedVariables); try { for (int i = 0; i < numCheckedVariables; i++) { var variable = new OutDeconstructVarPendingInference(receiverSyntax); analyzedArguments.Arguments.Add(variable); analyzedArguments.RefKinds.Add(RefKind.Out); outVars.Add(variable); } const string methodName = WellKnownMemberNames.DeconstructMethodName; var memberAccess = BindInstanceMemberAccess( rightSyntax, receiverSyntax, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: true, indexed: false, diagnostics: diagnostics); memberAccess = CheckValue(memberAccess, BindValueKind.RValueOrMethodGroup, diagnostics); memberAccess.WasCompilerGenerated = true; if (memberAccess.Kind != BoundKind.MethodGroup) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver); } // After the overload resolution completes, the last step is to coerce the arguments with inferred types. // That step returns placeholder (of correct type) instead of the outVar nodes that were passed in as arguments. // So the generated invocation expression will contain placeholders instead of those outVar nodes. // Those placeholders are also recorded in the outVar for easy access below, by the `SetInferredType` call on the outVar nodes. BoundExpression result = BindMethodGroupInvocation( rightSyntax, rightSyntax, methodName, (BoundMethodGroup)memberAccess, analyzedArguments, diagnostics, queryClause: null, allowUnexpandedForm: true, anyApplicableCandidates: out anyApplicableCandidates); result.WasCompilerGenerated = true; if (!anyApplicableCandidates) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } // Verify all the parameters (except "this" for extension methods) are out parameters. // This prevents, for example, an unused params parameter after the out parameters. var deconstructMethod = ((BoundCall)result).Method; var parameters = deconstructMethod.Parameters; for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) { if (parameters[i].RefKind != RefKind.Out) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } } if (deconstructMethod.ReturnType.GetSpecialTypeSafe() != SpecialType.System_Void) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } if (outVars.Any(v => v.Placeholder is null)) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } outPlaceholders = outVars.SelectAsArray(v => v.Placeholder!); return result; } finally { analyzedArguments.Free(); outVars.Free(); } } private BoundBadExpression MissingDeconstruct(BoundExpression receiver, SyntaxNode rightSyntax, int numParameters, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, BoundExpression childNode) { if (receiver.Type?.IsErrorType() == false) { Error(diagnostics, ErrorCode.ERR_MissingDeconstruct, rightSyntax, receiver.Type!, numParameters); } outPlaceholders = default; return BadExpression(rightSyntax, childNode); } /// <summary> /// Prepares locals (or fields in global statement) and lvalue expressions corresponding to the variables of the declaration. /// The locals/fields/lvalues are kept in a tree which captures the nesting of variables. /// Each local or field is either a simple local or field access (when its type is known) or a deconstruction variable pending inference. /// The caller is responsible for releasing the nested ArrayBuilders. /// </summary> private DeconstructionVariable BindDeconstructionVariables( ExpressionSyntax node, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var component = (DeclarationExpressionSyntax)node; if (declaration == null) { declaration = component; } bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(component.Designation, diagnostics, component.Type, ref isConst, out isVar, out alias); Debug.Assert(isVar == !declType.HasType); if (component.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation && !isVar) { // An explicit is not allowed with a parenthesized designation Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, component.Designation); } return BindDeconstructionVariables(declType, component.Designation, component, diagnostics); } case SyntaxKind.TupleExpression: { var component = (TupleExpressionSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(component.Arguments.Count); foreach (var arg in component.Arguments) { if (arg.NameColon != null) { Error(diagnostics, ErrorCode.ERR_TupleElementNamesInDeconstruction, arg.NameColon); } builder.Add(BindDeconstructionVariables(arg.Expression, diagnostics, ref declaration, ref expression)); } return new DeconstructionVariable(builder, node); } default: var boundVariable = BindExpression(node, diagnostics, invoked: false, indexed: false); var checkedVariable = CheckValue(boundVariable, BindValueKind.Assignable, diagnostics); if (expression == null && checkedVariable.Kind != BoundKind.DiscardExpression) { expression = node; } return new DeconstructionVariable(checkedVariable, node); } } private DeconstructionVariable BindDeconstructionVariables( TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; return new DeconstructionVariable(BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics), syntax); } case SyntaxKind.DiscardDesignation: { var discarded = (DiscardDesignationSyntax)node; return new DeconstructionVariable(BindDiscardExpression(syntax, declTypeWithAnnotations), syntax); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(); foreach (var n in tuple.Variables) { builder.Add(BindDeconstructionVariables(declTypeWithAnnotations, n, n, diagnostics)); } return new DeconstructionVariable(builder, syntax); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private static BoundDiscardExpression BindDiscardExpression( SyntaxNode syntax, TypeWithAnnotations declTypeWithAnnotations) { return new BoundDiscardExpression(syntax, declTypeWithAnnotations.Type); } /// <summary> /// In embedded statements, returns a BoundLocal when the type was explicit. /// In global statements, returns a BoundFieldAccess when the type was explicit. /// Otherwise returns a DeconstructionVariablePendingInference when the type is implicit. /// </summary> private BoundExpression BindDeconstructionVariable( TypeWithAnnotations declTypeWithAnnotations, SingleVariableDesignationSyntax designation, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { SourceLocalSymbol localSymbol = LookupLocal(designation.Identifier); // is this a local? if ((object)localSymbol != null) { // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. var hasErrors = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (declTypeWithAnnotations.HasType) { return new BoundLocal(syntax, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declTypeWithAnnotations.Type, hasErrors: hasErrors); } return new DeconstructionVariablePendingInference(syntax, localSymbol, receiverOpt: null); } // Is this a field? GlobalExpressionVariable field = LookupDeclaredField(designation); if ((object)field == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundThisReference receiver = ThisReference(designation, this.ContainingType, hasErrors: false, wasCompilerGenerated: true); if (declTypeWithAnnotations.HasType) { var fieldType = field.GetFieldType(this.FieldsBeingBound); Debug.Assert(TypeSymbol.Equals(declTypeWithAnnotations.Type, fieldType.Type, TypeCompareKind.ConsiderEverything2)); return new BoundFieldAccess(syntax, receiver, field, constantValueOpt: null, resultKind: LookupResultKind.Viable, isDeclaration: true, type: fieldType.Type); } return new DeconstructionVariablePendingInference(syntax, field, receiver); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts deconstruction-assignment syntax (AssignmentExpressionSyntax nodes with the left /// being a tuple expression or declaration expression) into a BoundDeconstructionAssignmentOperator (or bad node). /// The BoundDeconstructionAssignmentOperator will have: /// - a BoundTupleLiteral as its Left, /// - a BoundConversion as its Right, holding: /// - a tree of Conversion objects with Kind=Deconstruction, information about a Deconstruct method (optional) and /// an array of nested Conversions (like a tuple conversion), /// - a BoundExpression as its Operand. /// </summary> internal partial class Binder { internal BoundExpression BindDeconstruction(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics, bool resultIsUsedOverride = false) { var left = node.Left; var right = node.Right; DeclarationExpressionSyntax? declaration = null; ExpressionSyntax? expression = null; var result = BindDeconstruction(node, left, right, diagnostics, ref declaration, ref expression, resultIsUsedOverride); if (declaration != null) { // only allowed at the top level, or in a for loop switch (node.Parent?.Kind()) { case null: case SyntaxKind.ExpressionStatement: if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } break; case SyntaxKind.ForStatement: if (((ForStatementSyntax)node.Parent).Initializers.Contains(node)) { if (expression != null) { MessageID.IDS_FeatureMixedDeclarationsAndExpressionsInDeconstruction .CheckFeatureAvailability(diagnostics, Compilation, node.Location); } } else { Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); } break; default: Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, declaration); break; } } return result; } /// <summary> /// Bind a deconstruction assignment. /// </summary> /// <param name="deconstruction">The deconstruction operation</param> /// <param name="left">The left (tuple) operand</param> /// <param name="right">The right (deconstructable) operand</param> /// <param name="diagnostics">Where to report diagnostics</param> /// <param name="declaration">A variable set to the first variable declaration found in the left</param> /// <param name="expression">A variable set to the first expression in the left that isn't a declaration or discard</param> /// <param name="resultIsUsedOverride">The expression evaluator needs to bind deconstructions (both assignments and declarations) as expression-statements /// and still access the returned value</param> /// <param name="rightPlaceholder"></param> /// <returns></returns> internal BoundDeconstructionAssignmentOperator BindDeconstruction( CSharpSyntaxNode deconstruction, ExpressionSyntax left, ExpressionSyntax right, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression, bool resultIsUsedOverride = false, BoundDeconstructValuePlaceholder? rightPlaceholder = null) { DeconstructionVariable locals = BindDeconstructionVariables(left, diagnostics, ref declaration, ref expression); Debug.Assert(locals.NestedVariables is object); var deconstructionDiagnostics = new BindingDiagnosticBag(new DiagnosticBag(), diagnostics.DependenciesBag); BoundExpression boundRight = rightPlaceholder ?? BindValue(right, deconstructionDiagnostics, BindValueKind.RValue); boundRight = FixTupleLiteral(locals.NestedVariables, boundRight, deconstruction, deconstructionDiagnostics); boundRight = BindToNaturalType(boundRight, diagnostics); bool resultIsUsed = resultIsUsedOverride || IsDeconstructionResultUsed(left); var assignment = BindDeconstructionAssignment(deconstruction, left, boundRight, locals.NestedVariables, resultIsUsed, deconstructionDiagnostics); DeconstructionVariable.FreeDeconstructionVariables(locals.NestedVariables); diagnostics.AddRange(deconstructionDiagnostics.DiagnosticBag); return assignment; } private BoundDeconstructionAssignmentOperator BindDeconstructionAssignment( CSharpSyntaxNode node, ExpressionSyntax left, BoundExpression boundRHS, ArrayBuilder<DeconstructionVariable> checkedVariables, bool resultIsUsed, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); uint rightEscape = GetValEscape(boundRHS, this.LocalScopeDepth); if ((object?)boundRHS.Type == null || boundRHS.Type.IsErrorType()) { // we could still not infer a type for the RHS FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var voidType = GetSpecialType(SpecialType.System_Void, diagnostics, node); var type = boundRHS.Type ?? voidType; return new BoundDeconstructionAssignmentOperator( node, DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: true), new BoundConversion(boundRHS.Syntax, boundRHS, Conversion.Deconstruction, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: type, hasErrors: true), resultIsUsed, voidType, hasErrors: true); } Conversion conversion; bool hasErrors = !MakeDeconstructionConversion( boundRHS.Type, node, boundRHS.Syntax, diagnostics, checkedVariables, out conversion); if (conversion.Method != null) { CheckImplicitThisCopyInReadOnlyMember(boundRHS, conversion.Method, diagnostics); } FailRemainingInferencesAndSetValEscape(checkedVariables, diagnostics, rightEscape); var lhsTuple = DeconstructionVariablesAsTuple(left, checkedVariables, diagnostics, ignoreDiagnosticsFromTuple: diagnostics.HasAnyErrors() || !resultIsUsed); Debug.Assert(hasErrors || lhsTuple.Type is object); TypeSymbol returnType = hasErrors ? CreateErrorType() : lhsTuple.Type!; uint leftEscape = GetBroadestValEscape(lhsTuple, this.LocalScopeDepth); boundRHS = ValidateEscape(boundRHS, leftEscape, isByRef: false, diagnostics: diagnostics); var boundConversion = new BoundConversion( boundRHS.Syntax, boundRHS, conversion, @checked: false, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, type: returnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; return new BoundDeconstructionAssignmentOperator(node, lhsTuple, boundConversion, resultIsUsed, returnType); } private static bool IsDeconstructionResultUsed(ExpressionSyntax left) { var parent = left.Parent; if (parent is null || parent.Kind() == SyntaxKind.ForEachVariableStatement) { return false; } Debug.Assert(parent.Kind() == SyntaxKind.SimpleAssignmentExpression); var grandParent = parent.Parent; if (grandParent is null) { return false; } switch (grandParent.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)grandParent).Expression != parent; case SyntaxKind.ForStatement: // Incrementors and Initializers don't have to produce a value var loop = (ForStatementSyntax)grandParent; return !loop.Incrementors.Contains(parent) && !loop.Initializers.Contains(parent); default: return true; } } /// <summary>When boundRHS is a tuple literal, fix it up by inferring its types.</summary> private BoundExpression FixTupleLiteral(ArrayBuilder<DeconstructionVariable> checkedVariables, BoundExpression boundRHS, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag is object); if (boundRHS.Kind == BoundKind.TupleLiteral) { // Let's fix the literal up by figuring out its type // For declarations, that means merging type information from the LHS and RHS // For assignments, only the LHS side matters since it is necessarily typed // If we already have diagnostics at this point, it is not worth collecting likely duplicate diagnostics from making the merged type bool hadErrors = diagnostics.HasAnyErrors(); TypeSymbol? mergedTupleType = MakeMergedTupleType(checkedVariables, (BoundTupleLiteral)boundRHS, syntax, hadErrors ? null : diagnostics); if ((object?)mergedTupleType != null) { boundRHS = GenerateConversionForAssignment(mergedTupleType, boundRHS, diagnostics); } } else if ((object?)boundRHS.Type == null) { Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, boundRHS.Syntax); } return boundRHS; } /// <summary> /// Recursively builds a Conversion object with Kind=Deconstruction including information about any necessary /// Deconstruct method and any element-wise conversion. /// /// Note that the variables may either be plain or nested variables. /// The variables may be updated with inferred types if they didn't have types initially. /// Returns false if there was an error. /// </summary> private bool MakeDeconstructionConversion( TypeSymbol type, SyntaxNode syntax, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, ArrayBuilder<DeconstructionVariable> variables, out Conversion conversion) { Debug.Assert((object)type != null); ImmutableArray<TypeSymbol> tupleOrDeconstructedTypes; conversion = Conversion.Deconstruction; // Figure out the deconstruct method (if one is required) and determine the types we get from the RHS at this level var deconstructMethod = default(DeconstructMethodInfo); if (type.IsTupleType) { // tuple literal such as `(1, 2)`, `(null, null)`, `(x.P, y.M())` tupleOrDeconstructedTypes = type.TupleElementTypesWithAnnotations.SelectAsArray(TypeMap.AsTypeSymbol); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); if (variables.Count != tupleOrDeconstructedTypes.Length) { Error(diagnostics, ErrorCode.ERR_DeconstructWrongCardinality, syntax, tupleOrDeconstructedTypes.Length, variables.Count); return false; } } else { if (variables.Count < 2) { Error(diagnostics, ErrorCode.ERR_DeconstructTooFewElements, syntax); return false; } var inputPlaceholder = new BoundDeconstructValuePlaceholder(syntax, this.LocalScopeDepth, type); BoundExpression deconstructInvocation = MakeDeconstructInvocationExpression(variables.Count, inputPlaceholder, rightSyntax, diagnostics, outPlaceholders: out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out _); if (deconstructInvocation.HasAnyErrors) { return false; } deconstructMethod = new DeconstructMethodInfo(deconstructInvocation, inputPlaceholder, outPlaceholders); tupleOrDeconstructedTypes = outPlaceholders.SelectAsArray(p => p.Type); SetInferredTypes(variables, tupleOrDeconstructedTypes, diagnostics); } // Figure out whether those types will need conversions, including further deconstructions bool hasErrors = false; int count = variables.Count; var nestedConversions = ArrayBuilder<Conversion>.GetInstance(count); for (int i = 0; i < count; i++) { var variable = variables[i]; Conversion nestedConversion; if (variable.NestedVariables is object) { var elementSyntax = syntax.Kind() == SyntaxKind.TupleExpression ? ((TupleExpressionSyntax)syntax).Arguments[i] : syntax; hasErrors |= !MakeDeconstructionConversion(tupleOrDeconstructedTypes[i], elementSyntax, rightSyntax, diagnostics, variable.NestedVariables, out nestedConversion); } else { var single = variable.Single; Debug.Assert(single is object); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); nestedConversion = this.Conversions.ClassifyConversionFromType(tupleOrDeconstructedTypes[i], single.Type, ref useSiteInfo); diagnostics.Add(single.Syntax, useSiteInfo); if (!nestedConversion.IsImplicit) { hasErrors = true; GenerateImplicitConversionError(diagnostics, Compilation, single.Syntax, nestedConversion, tupleOrDeconstructedTypes[i], single.Type); } } nestedConversions.Add(nestedConversion); } conversion = new Conversion(ConversionKind.Deconstruction, deconstructMethod, nestedConversions.ToImmutableAndFree()); return !hasErrors; } /// <summary> /// Inform the variables about found types. /// </summary> private void SetInferredTypes(ArrayBuilder<DeconstructionVariable> variables, ImmutableArray<TypeSymbol> foundTypes, BindingDiagnosticBag diagnostics) { var matchCount = Math.Min(variables.Count, foundTypes.Length); for (int i = 0; i < matchCount; i++) { var variable = variables[i]; if (variable.Single is { } pending) { if ((object?)pending.Type != null) { continue; } variables[i] = new DeconstructionVariable(SetInferredType(pending, foundTypes[i], diagnostics), variable.Syntax); } } } private BoundExpression SetInferredType(BoundExpression expression, TypeSymbol type, BindingDiagnosticBag diagnostics) { switch (expression.Kind) { case BoundKind.DeconstructionVariablePendingInference: { var pending = (DeconstructionVariablePendingInference)expression; return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type), this, diagnostics); } case BoundKind.DiscardExpression: { var pending = (BoundDiscardExpression)expression; Debug.Assert((object?)pending.Type == null); return pending.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(type)); } default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Find any deconstruction locals that are still pending inference and fail their inference. /// Set the safe-to-escape scope for all deconstruction locals. /// </summary> private void FailRemainingInferencesAndSetValEscape(ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, uint rhsValEscape) { int count = variables.Count; for (int i = 0; i < count; i++) { var variable = variables[i]; if (variable.NestedVariables is object) { FailRemainingInferencesAndSetValEscape(variable.NestedVariables, diagnostics, rhsValEscape); } else { Debug.Assert(variable.Single is object); switch (variable.Single.Kind) { case BoundKind.Local: var local = (BoundLocal)variable.Single; if (local.DeclarationKind != BoundLocalDeclarationKind.None) { ((SourceLocalSymbol)local.LocalSymbol).SetValEscape(rhsValEscape); } break; case BoundKind.DeconstructionVariablePendingInference: BoundExpression errorLocal = ((DeconstructionVariablePendingInference)variable.Single).FailInference(this, diagnostics); variables[i] = new DeconstructionVariable(errorLocal, errorLocal.Syntax); break; case BoundKind.DiscardExpression: var pending = (BoundDiscardExpression)variable.Single; if ((object?)pending.Type == null) { Error(diagnostics, ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, pending.Syntax, "_"); variables[i] = new DeconstructionVariable(pending.FailInference(this, diagnostics), pending.Syntax); } break; } // at this point we expect to have a type for every lvalue Debug.Assert((object?)variables[i].Single!.Type != null); } } } /// <summary> /// Holds the variables on the LHS of a deconstruction as a tree of bound expressions. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class DeconstructionVariable { internal readonly BoundExpression? Single; internal readonly ArrayBuilder<DeconstructionVariable>? NestedVariables; internal readonly CSharpSyntaxNode Syntax; internal DeconstructionVariable(BoundExpression variable, SyntaxNode syntax) { Single = variable; NestedVariables = null; Syntax = (CSharpSyntaxNode)syntax; } internal DeconstructionVariable(ArrayBuilder<DeconstructionVariable> variables, SyntaxNode syntax) { Single = null; NestedVariables = variables; Syntax = (CSharpSyntaxNode)syntax; } internal static void FreeDeconstructionVariables(ArrayBuilder<DeconstructionVariable> variables) { variables.FreeAll(v => v.NestedVariables); } private string GetDebuggerDisplay() { if (Single != null) { return Single.GetDebuggerDisplay(); } Debug.Assert(NestedVariables is object); return $"Nested variables ({NestedVariables.Count})"; } } /// <summary> /// For cases where the RHS of a deconstruction-declaration is a tuple literal, we merge type information from both the LHS and RHS. /// For cases where the RHS of a deconstruction-assignment is a tuple literal, the type information from the LHS determines the merged type, since all variables have a type. /// Returns null if a merged tuple type could not be fabricated. /// </summary> private TypeSymbol? MakeMergedTupleType(ArrayBuilder<DeconstructionVariable> lhsVariables, BoundTupleLiteral rhsLiteral, CSharpSyntaxNode syntax, BindingDiagnosticBag? diagnostics) { int leftLength = lhsVariables.Count; int rightLength = rhsLiteral.Arguments.Length; var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(leftLength); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(leftLength); for (int i = 0; i < rightLength; i++) { BoundExpression element = rhsLiteral.Arguments[i]; TypeSymbol? mergedType = element.Type; if (i < leftLength) { var variable = lhsVariables[i]; if (variable.NestedVariables is object) { if (element.Kind == BoundKind.TupleLiteral) { // (variables) on the left and (elements) on the right mergedType = MakeMergedTupleType(variable.NestedVariables, (BoundTupleLiteral)element, syntax, diagnostics); } else if ((object?)mergedType == null && diagnostics is object) { // (variables) on the left and null on the right Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } else { Debug.Assert(variable.Single is object); if ((object?)variable.Single.Type != null) { // typed-variable on the left mergedType = variable.Single.Type; } } } else { if ((object?)mergedType == null && diagnostics is object) { // a typeless element on the right, matching no variable on the left Error(diagnostics, ErrorCode.ERR_DeconstructRequiresExpression, element.Syntax); } } typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(mergedType)); locationsBuilder.Add(element.Syntax.Location); } if (typesWithAnnotationsBuilder.Any(t => !t.HasType)) { typesWithAnnotationsBuilder.Free(); locationsBuilder.Free(); return null; } // The tuple created here is not identical to the one created by // DeconstructionVariablesAsTuple. It represents a smaller // tree of types used for figuring out natural types in tuple literal. return NamedTypeSymbol.CreateTuple( locationOpt: null, elementTypesWithAnnotations: typesWithAnnotationsBuilder.ToImmutableAndFree(), elementLocations: locationsBuilder.ToImmutableAndFree(), elementNames: default(ImmutableArray<string?>), compilation: Compilation, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: default(ImmutableArray<bool>), syntax: syntax); } private BoundTupleExpression DeconstructionVariablesAsTuple(CSharpSyntaxNode syntax, ArrayBuilder<DeconstructionVariable> variables, BindingDiagnosticBag diagnostics, bool ignoreDiagnosticsFromTuple) { int count = variables.Count; var valuesBuilder = ArrayBuilder<BoundExpression>.GetInstance(count); var typesWithAnnotationsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(count); var locationsBuilder = ArrayBuilder<Location?>.GetInstance(count); var namesBuilder = ArrayBuilder<string?>.GetInstance(count); foreach (var variable in variables) { BoundExpression value; if (variable.NestedVariables is object) { value = DeconstructionVariablesAsTuple(variable.Syntax, variable.NestedVariables, diagnostics, ignoreDiagnosticsFromTuple); namesBuilder.Add(null); } else { Debug.Assert(variable.Single is object); value = variable.Single; namesBuilder.Add(ExtractDeconstructResultElementName(value)); } valuesBuilder.Add(value); typesWithAnnotationsBuilder.Add(TypeWithAnnotations.Create(value.Type)); locationsBuilder.Add(variable.Syntax.Location); } ImmutableArray<BoundExpression> arguments = valuesBuilder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string?> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); var type = NamedTypeSymbol.CreateTuple( syntax.Location, typesWithAnnotationsBuilder.ToImmutableAndFree(), locationsBuilder.ToImmutableAndFree(), tupleNames, this.Compilation, shouldCheckConstraints: !ignoreDiagnosticsFromTuple, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default, syntax: syntax, diagnostics: ignoreDiagnosticsFromTuple ? null : diagnostics); return (BoundTupleExpression)BindToNaturalType(new BoundTupleLiteral(syntax, arguments, tupleNames, inferredPositions, type), diagnostics); } /// <summary>Extract inferred name from a single deconstruction variable.</summary> private static string? ExtractDeconstructResultElementName(BoundExpression expression) { if (expression.Kind == BoundKind.DiscardExpression) { return null; } return InferTupleElementName(expression.Syntax); } /// <summary> /// Find the Deconstruct method for the expression on the right, that will fit the number of assignable variables on the left. /// Returns an invocation expression if the Deconstruct method is found. /// If so, it outputs placeholders that were coerced to the output types of the resolved Deconstruct method. /// The overload resolution is similar to writing <c>receiver.Deconstruct(out var x1, out var x2, ...)</c>. /// </summary> private BoundExpression MakeDeconstructInvocationExpression( int numCheckedVariables, BoundExpression receiver, SyntaxNode rightSyntax, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, out bool anyApplicableCandidates) { anyApplicableCandidates = false; var receiverSyntax = (CSharpSyntaxNode)receiver.Syntax; if (receiver.Type?.IsDynamic() ?? false) { Error(diagnostics, ErrorCode.ERR_CannotDeconstructDynamic, rightSyntax); outPlaceholders = default(ImmutableArray<BoundDeconstructValuePlaceholder>); return BadExpression(receiverSyntax, receiver); } receiver = BindToNaturalType(receiver, diagnostics); var analyzedArguments = AnalyzedArguments.GetInstance(); var outVars = ArrayBuilder<OutDeconstructVarPendingInference>.GetInstance(numCheckedVariables); try { for (int i = 0; i < numCheckedVariables; i++) { var variable = new OutDeconstructVarPendingInference(receiverSyntax); analyzedArguments.Arguments.Add(variable); analyzedArguments.RefKinds.Add(RefKind.Out); outVars.Add(variable); } const string methodName = WellKnownMemberNames.DeconstructMethodName; var memberAccess = BindInstanceMemberAccess( rightSyntax, receiverSyntax, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: true, indexed: false, diagnostics: diagnostics); memberAccess = CheckValue(memberAccess, BindValueKind.RValueOrMethodGroup, diagnostics); memberAccess.WasCompilerGenerated = true; if (memberAccess.Kind != BoundKind.MethodGroup) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, receiver); } // After the overload resolution completes, the last step is to coerce the arguments with inferred types. // That step returns placeholder (of correct type) instead of the outVar nodes that were passed in as arguments. // So the generated invocation expression will contain placeholders instead of those outVar nodes. // Those placeholders are also recorded in the outVar for easy access below, by the `SetInferredType` call on the outVar nodes. BoundExpression result = BindMethodGroupInvocation( rightSyntax, rightSyntax, methodName, (BoundMethodGroup)memberAccess, analyzedArguments, diagnostics, queryClause: null, allowUnexpandedForm: true, anyApplicableCandidates: out anyApplicableCandidates); result.WasCompilerGenerated = true; if (!anyApplicableCandidates) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } // Verify all the parameters (except "this" for extension methods) are out parameters. // This prevents, for example, an unused params parameter after the out parameters. var deconstructMethod = ((BoundCall)result).Method; var parameters = deconstructMethod.Parameters; for (int i = (deconstructMethod.IsExtensionMethod ? 1 : 0); i < parameters.Length; i++) { if (parameters[i].RefKind != RefKind.Out) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } } if (deconstructMethod.ReturnType.GetSpecialTypeSafe() != SpecialType.System_Void) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } if (outVars.Any(v => v.Placeholder is null)) { return MissingDeconstruct(receiver, rightSyntax, numCheckedVariables, diagnostics, out outPlaceholders, result); } outPlaceholders = outVars.SelectAsArray(v => v.Placeholder!); return result; } finally { analyzedArguments.Free(); outVars.Free(); } } private BoundBadExpression MissingDeconstruct(BoundExpression receiver, SyntaxNode rightSyntax, int numParameters, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundDeconstructValuePlaceholder> outPlaceholders, BoundExpression childNode) { if (receiver.Type?.IsErrorType() == false) { Error(diagnostics, ErrorCode.ERR_MissingDeconstruct, rightSyntax, receiver.Type!, numParameters); } outPlaceholders = default; return BadExpression(rightSyntax, childNode); } /// <summary> /// Prepares locals (or fields in global statement) and lvalue expressions corresponding to the variables of the declaration. /// The locals/fields/lvalues are kept in a tree which captures the nesting of variables. /// Each local or field is either a simple local or field access (when its type is known) or a deconstruction variable pending inference. /// The caller is responsible for releasing the nested ArrayBuilders. /// </summary> private DeconstructionVariable BindDeconstructionVariables( ExpressionSyntax node, BindingDiagnosticBag diagnostics, ref DeclarationExpressionSyntax? declaration, ref ExpressionSyntax? expression) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var component = (DeclarationExpressionSyntax)node; if (declaration == null) { declaration = component; } bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(component.Designation, diagnostics, component.Type, ref isConst, out isVar, out alias); Debug.Assert(isVar == !declType.HasType); if (component.Designation.Kind() == SyntaxKind.ParenthesizedVariableDesignation && !isVar) { // An explicit is not allowed with a parenthesized designation Error(diagnostics, ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, component.Designation); } return BindDeconstructionVariables(declType, component.Designation, component, diagnostics); } case SyntaxKind.TupleExpression: { var component = (TupleExpressionSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(component.Arguments.Count); foreach (var arg in component.Arguments) { if (arg.NameColon != null) { Error(diagnostics, ErrorCode.ERR_TupleElementNamesInDeconstruction, arg.NameColon); } builder.Add(BindDeconstructionVariables(arg.Expression, diagnostics, ref declaration, ref expression)); } return new DeconstructionVariable(builder, node); } default: var boundVariable = BindExpression(node, diagnostics, invoked: false, indexed: false); var checkedVariable = CheckValue(boundVariable, BindValueKind.Assignable, diagnostics); if (expression == null && checkedVariable.Kind != BoundKind.DiscardExpression) { expression = node; } return new DeconstructionVariable(checkedVariable, node); } } private DeconstructionVariable BindDeconstructionVariables( TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; return new DeconstructionVariable(BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics), syntax); } case SyntaxKind.DiscardDesignation: { var discarded = (DiscardDesignationSyntax)node; return new DeconstructionVariable(BindDiscardExpression(syntax, declTypeWithAnnotations), syntax); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; var builder = ArrayBuilder<DeconstructionVariable>.GetInstance(); foreach (var n in tuple.Variables) { builder.Add(BindDeconstructionVariables(declTypeWithAnnotations, n, n, diagnostics)); } return new DeconstructionVariable(builder, syntax); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private static BoundDiscardExpression BindDiscardExpression( SyntaxNode syntax, TypeWithAnnotations declTypeWithAnnotations) { return new BoundDiscardExpression(syntax, declTypeWithAnnotations.Type); } /// <summary> /// In embedded statements, returns a BoundLocal when the type was explicit. /// In global statements, returns a BoundFieldAccess when the type was explicit. /// Otherwise returns a DeconstructionVariablePendingInference when the type is implicit. /// </summary> private BoundExpression BindDeconstructionVariable( TypeWithAnnotations declTypeWithAnnotations, SingleVariableDesignationSyntax designation, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { SourceLocalSymbol localSymbol = LookupLocal(designation.Identifier); // is this a local? if ((object)localSymbol != null) { // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. var hasErrors = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (declTypeWithAnnotations.HasType) { return new BoundLocal(syntax, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declTypeWithAnnotations.Type, hasErrors: hasErrors); } return new DeconstructionVariablePendingInference(syntax, localSymbol, receiverOpt: null); } // Is this a field? GlobalExpressionVariable field = LookupDeclaredField(designation); if ((object)field == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundThisReference receiver = ThisReference(designation, this.ContainingType, hasErrors: false, wasCompilerGenerated: true); if (declTypeWithAnnotations.HasType) { var fieldType = field.GetFieldType(this.FieldsBeingBound); Debug.Assert(TypeSymbol.Equals(declTypeWithAnnotations.Type, fieldType.Type, TypeCompareKind.ConsiderEverything2)); return new BoundFieldAccess(syntax, receiver, field, constantValueOpt: null, resultKind: LookupResultKind.Viable, isDeclaration: true, type: fieldType.Type); } return new DeconstructionVariablePendingInference(syntax, field, receiver); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Emitter/Model/ModuleReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ModuleReference : Cci.IModuleReference, Cci.IFileReference { private readonly PEModuleBuilder _moduleBeingBuilt; private readonly ModuleSymbol _underlyingModule; internal ModuleReference(PEModuleBuilder moduleBeingBuilt, ModuleSymbol underlyingModule) { Debug.Assert(moduleBeingBuilt != null); Debug.Assert((object)underlyingModule != null); _moduleBeingBuilt = moduleBeingBuilt; _underlyingModule = underlyingModule; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IModuleReference)this); } string Cci.INamedEntity.Name { get { return _underlyingModule.MetadataName; } } bool Cci.IFileReference.HasMetadata { get { return true; } } string Cci.IFileReference.FileName { get { return _underlyingModule.Name; } } ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId) { return _underlyingModule.GetHash(algorithmId); } Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { if (_moduleBeingBuilt.OutputKind.IsNetModule() && ReferenceEquals(_moduleBeingBuilt.SourceModule.ContainingAssembly, _underlyingModule.ContainingAssembly)) { return null; } return _moduleBeingBuilt.Translate(_underlyingModule.ContainingAssembly, context.Diagnostics); } public override string ToString() { return _underlyingModule.ToString(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => 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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ModuleReference : Cci.IModuleReference, Cci.IFileReference { private readonly PEModuleBuilder _moduleBeingBuilt; private readonly ModuleSymbol _underlyingModule; internal ModuleReference(PEModuleBuilder moduleBeingBuilt, ModuleSymbol underlyingModule) { Debug.Assert(moduleBeingBuilt != null); Debug.Assert((object)underlyingModule != null); _moduleBeingBuilt = moduleBeingBuilt; _underlyingModule = underlyingModule; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.IModuleReference)this); } string Cci.INamedEntity.Name { get { return _underlyingModule.MetadataName; } } bool Cci.IFileReference.HasMetadata { get { return true; } } string Cci.IFileReference.FileName { get { return _underlyingModule.Name; } } ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId) { return _underlyingModule.GetHash(algorithmId); } Cci.IAssemblyReference Cci.IModuleReference.GetContainingAssembly(EmitContext context) { if (_moduleBeingBuilt.OutputKind.IsNetModule() && ReferenceEquals(_moduleBeingBuilt.SourceModule.ContainingAssembly, _underlyingModule.ContainingAssembly)) { return null; } return _moduleBeingBuilt.Translate(_underlyingModule.ContainingAssembly, context.Diagnostics); } public override string ToString() { return _underlyingModule.ToString(); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/CSharp/Portable/GenerateConstructor/CSharpGenerateConstructorService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateConstructorService() { } protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is SimpleNameSyntax; protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ConstructorInitializerSyntax; protected override bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ImplicitObjectCreationExpressionSyntax; protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = GetArguments(constructorInitializer.ArgumentList.Arguments); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default; arguments = default; typeToGenerateIn = null; return false; } private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument(a.GetRefKind(), a.NameColon?.Name.Identifier.ValueText, a.Expression)); private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument( refKind: RefKind.None, a.NameEquals?.Name.Identifier.ValueText ?? a.NameColon?.Name.Identifier.ValueText, a.Expression)); protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax objectCreationExpression) { if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = GetArguments(objectCreationExpression.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax attribute) { if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; arguments = GetArguments(attribute.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var implicitObjectCreation = (ImplicitObjectCreationExpressionSyntax)node; if (implicitObjectCreation.ArgumentList != null && !implicitObjectCreation.ArgumentList.CloseParenToken.IsMissing) { var typeInfo = document.SemanticModel.GetTypeInfo(implicitObjectCreation, cancellationToken); if (typeInfo.Type is INamedTypeSymbol typeSymbol) { token = implicitObjectCreation.NewKeyword; arguments = GetArguments(implicitObjectCreation.ArgumentList.Arguments); typeToGenerateIn = typeSymbol; return true; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override string GenerateNameForExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) => semanticModel.GenerateNameForExpression(expression, capitalize: false, cancellationToken: cancellationToken); protected override ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) => InternalExtensions.DetermineParameterType(argument.Expression, semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; protected override IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => token.GetAncestor<ConstructorDeclarationSyntax>() is { } constructor ? semanticModel.GetDeclaredSymbol(constructor, cancellationToken) : null; protected override IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken) { if (constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) is ConstructorDeclarationSyntax constructorDeclarationSyntax && constructorDeclarationSyntax.Initializer.IsKind(SyntaxKind.ThisConstructorInitializer)) { return semanticModel.GetSymbolInfo(constructorDeclarationSyntax.Initializer, cancellationToken).Symbol as IMethodSymbol; } 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.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateConstructorService() { } protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is SimpleNameSyntax; protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ConstructorInitializerSyntax; protected override bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ImplicitObjectCreationExpressionSyntax; protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = GetArguments(constructorInitializer.ArgumentList.Arguments); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default; arguments = default; typeToGenerateIn = null; return false; } private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument(a.GetRefKind(), a.NameColon?.Name.Identifier.ValueText, a.Expression)); private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument( refKind: RefKind.None, a.NameEquals?.Name.Identifier.ValueText ?? a.NameColon?.Name.Identifier.ValueText, a.Expression)); protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax objectCreationExpression) { if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = GetArguments(objectCreationExpression.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax attribute) { if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; arguments = GetArguments(attribute.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var implicitObjectCreation = (ImplicitObjectCreationExpressionSyntax)node; if (implicitObjectCreation.ArgumentList != null && !implicitObjectCreation.ArgumentList.CloseParenToken.IsMissing) { var typeInfo = document.SemanticModel.GetTypeInfo(implicitObjectCreation, cancellationToken); if (typeInfo.Type is INamedTypeSymbol typeSymbol) { token = implicitObjectCreation.NewKeyword; arguments = GetArguments(implicitObjectCreation.ArgumentList.Arguments); typeToGenerateIn = typeSymbol; return true; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override string GenerateNameForExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) => semanticModel.GenerateNameForExpression(expression, capitalize: false, cancellationToken: cancellationToken); protected override ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) => InternalExtensions.DetermineParameterType(argument.Expression, semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; protected override IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => token.GetAncestor<ConstructorDeclarationSyntax>() is { } constructor ? semanticModel.GetDeclaredSymbol(constructor, cancellationToken) : null; protected override IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken) { if (constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) is ConstructorDeclarationSyntax constructorDeclarationSyntax && constructorDeclarationSyntax.Initializer.IsKind(SyntaxKind.ThisConstructorInitializer)) { return semanticModel.GetSymbolInfo(constructorDeclarationSyntax.Initializer, cancellationToken).Symbol as IMethodSymbol; } return null; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/Compilation/TypeInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public readonly struct TypeInfo : IEquatable<TypeInfo> { internal static readonly TypeInfo None = new TypeInfo(type: null, convertedType: null, nullability: default, convertedNullability: default); /// <summary> /// The type of the expression represented by the syntax node. For expressions that do not /// have a type, null is returned. If the type could not be determined due to an error, then /// an IErrorTypeSymbol is returned. /// </summary> public ITypeSymbol? Type { get; } /// <summary> /// The top-level nullability information of the expression represented by the syntax node. /// </summary> public NullabilityInfo Nullability { get; } /// <summary> /// The type of the expression after it has undergone an implicit conversion. If the type /// did not undergo an implicit conversion, returns the same as Type. /// </summary> public ITypeSymbol? ConvertedType { get; } /// <summary> /// The top-level nullability of the expression after it has undergone an implicit conversion. /// For most expressions, this will be the same as the type. It can change in situations such /// as implicit user-defined conversions that have a nullable return type. /// </summary> public NullabilityInfo ConvertedNullability { get; } internal TypeInfo(ITypeSymbol? type, ITypeSymbol? convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability) : this() { Debug.Assert(type is null || type.NullableAnnotation == nullability.FlowState.ToAnnotation()); Debug.Assert(convertedType is null || convertedType.NullableAnnotation == convertedNullability.FlowState.ToAnnotation()); this.Type = type; this.Nullability = nullability; this.ConvertedType = convertedType; this.ConvertedNullability = convertedNullability; } public bool Equals(TypeInfo other) { return object.Equals(this.Type, other.Type) && object.Equals(this.ConvertedType, other.ConvertedType) && this.Nullability.Equals(other.Nullability) && this.ConvertedNullability.Equals(other.ConvertedNullability); } public override bool Equals(object? obj) { return obj is TypeInfo && this.Equals((TypeInfo)obj); } public override int GetHashCode() { return Hash.Combine(this.ConvertedType, Hash.Combine(this.Type, Hash.Combine(this.Nullability.GetHashCode(), this.ConvertedNullability.GetHashCode()))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public readonly struct TypeInfo : IEquatable<TypeInfo> { internal static readonly TypeInfo None = new TypeInfo(type: null, convertedType: null, nullability: default, convertedNullability: default); /// <summary> /// The type of the expression represented by the syntax node. For expressions that do not /// have a type, null is returned. If the type could not be determined due to an error, then /// an IErrorTypeSymbol is returned. /// </summary> public ITypeSymbol? Type { get; } /// <summary> /// The top-level nullability information of the expression represented by the syntax node. /// </summary> public NullabilityInfo Nullability { get; } /// <summary> /// The type of the expression after it has undergone an implicit conversion. If the type /// did not undergo an implicit conversion, returns the same as Type. /// </summary> public ITypeSymbol? ConvertedType { get; } /// <summary> /// The top-level nullability of the expression after it has undergone an implicit conversion. /// For most expressions, this will be the same as the type. It can change in situations such /// as implicit user-defined conversions that have a nullable return type. /// </summary> public NullabilityInfo ConvertedNullability { get; } internal TypeInfo(ITypeSymbol? type, ITypeSymbol? convertedType, NullabilityInfo nullability, NullabilityInfo convertedNullability) : this() { Debug.Assert(type is null || type.NullableAnnotation == nullability.FlowState.ToAnnotation()); Debug.Assert(convertedType is null || convertedType.NullableAnnotation == convertedNullability.FlowState.ToAnnotation()); this.Type = type; this.Nullability = nullability; this.ConvertedType = convertedType; this.ConvertedNullability = convertedNullability; } public bool Equals(TypeInfo other) { return object.Equals(this.Type, other.Type) && object.Equals(this.ConvertedType, other.ConvertedType) && this.Nullability.Equals(other.Nullability) && this.ConvertedNullability.Equals(other.ConvertedNullability); } public override bool Equals(object? obj) { return obj is TypeInfo && this.Equals((TypeInfo)obj); } public override int GetHashCode() { return Hash.Combine(this.ConvertedType, Hash.Combine(this.Type, Hash.Combine(this.Nullability.GetHashCode(), this.ConvertedNullability.GetHashCode()))); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/Core/Portable/InitializeParameter/AbstractInitializeMemberFromParameterCodeRefactoringProviderMemberCreation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Naming; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InitializeParameter { internal abstract partial class AbstractInitializeMemberFromParameterCodeRefactoringProvider< TTypeDeclarationSyntax, TParameterSyntax, TStatementSyntax, TExpressionSyntax> : AbstractInitializeParameterCodeRefactoringProvider< TTypeDeclarationSyntax, TParameterSyntax, TStatementSyntax, TExpressionSyntax> where TTypeDeclarationSyntax : SyntaxNode where TParameterSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode { protected abstract SyntaxNode TryGetLastStatement(IBlockOperation? blockStatementOpt); protected abstract Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType); protected abstract Accessibility DetermineDefaultPropertyAccessibility(); protected override Task<ImmutableArray<CodeAction>> GetRefactoringsForAllParametersAsync( Document document, SyntaxNode functionDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<SyntaxNode> listOfParameterNodes, TextSpan parameterSpan, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<CodeAction>(); } protected override async Task<ImmutableArray<CodeAction>> GetRefactoringsForSingleParameterAsync( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, CancellationToken cancellationToken) { // Only supported for constructor parameters. if (method.MethodKind != MethodKind.Constructor) return ImmutableArray<CodeAction>.Empty; var typeDeclaration = constructorDeclaration.GetAncestor<TTypeDeclarationSyntax>(); if (typeDeclaration == null) return ImmutableArray<CodeAction>.Empty; // See if we're already assigning this parameter to a field/property in this type. If so, there's nothing // more for us to do. var assignmentStatement = TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt); if (assignmentStatement != null) return ImmutableArray<CodeAction>.Empty; // Haven't initialized any fields/properties with this parameter. Offer to assign // to an existing matching field/prop if we can find one, or add a new field/prop // if we can't. var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules); if (parameterNameParts.BaseName == "") return ImmutableArray<CodeAction>.Empty; var fieldOrProperty = await TryFindMatchingUninitializedFieldOrPropertySymbolAsync( document, parameter, blockStatementOpt, rules, parameterNameParts.BaseNameParts, cancellationToken).ConfigureAwait(false); if (fieldOrProperty != null) { return HandleExistingFieldOrProperty( document, parameter, constructorDeclaration, blockStatementOpt, fieldOrProperty); } return await HandleNoExistingFieldOrPropertyAsync( document, parameter, constructorDeclaration, method, blockStatementOpt, rules, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<CodeAction>> HandleNoExistingFieldOrPropertyAsync( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, CancellationToken cancellationToken) { // Didn't find a field/prop that this parameter could be assigned to. // Offer to create new one and assign to that. using var _ = ArrayBuilder<CodeAction>.GetInstance(out var allActions); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var (fieldAction, propertyAction) = AddSpecificParameterInitializationActions( document, parameter, constructorDeclaration, blockStatementOpt, rules, options); // Check if the surrounding parameters are assigned to another field in this class. If so, offer to // make this parameter into a field as well. Otherwise, default to generating a property var siblingFieldOrProperty = TryFindSiblingFieldOrProperty(parameter, blockStatementOpt); if (siblingFieldOrProperty is IFieldSymbol) { allActions.Add(fieldAction); allActions.Add(propertyAction); } else { allActions.Add(propertyAction); allActions.Add(fieldAction); } var (allFieldsAction, allPropertiesAction) = AddAllParameterInitializationActions( document, constructorDeclaration, method, blockStatementOpt, rules, options); if (allFieldsAction != null && allPropertiesAction != null) { if (siblingFieldOrProperty is IFieldSymbol) { allActions.Add(allFieldsAction); allActions.Add(allPropertiesAction); } else { allActions.Add(allPropertiesAction); allActions.Add(allFieldsAction); } } return allActions.ToImmutable(); } private (CodeAction? fieldAction, CodeAction? propertyAction) AddAllParameterInitializationActions( Document document, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, DocumentOptionSet options) { if (blockStatementOpt == null) return default; var parameters = GetParametersWithoutAssociatedMembers(blockStatementOpt, rules, method); if (parameters.Length < 2) return default; var fields = parameters.SelectAsArray(p => (ISymbol)CreateField(p, options, rules)); var properties = parameters.SelectAsArray(p => (ISymbol)CreateProperty(p, options, rules)); var allFieldsAction = new MyCodeAction( FeaturesResources.Create_and_assign_remaining_as_fields, c => AddAllSymbolInitializationsAsync( document, constructorDeclaration, blockStatementOpt, parameters, fields, c)); var allPropertiesAction = new MyCodeAction( FeaturesResources.Create_and_assign_remaining_as_properties, c => AddAllSymbolInitializationsAsync( document, constructorDeclaration, blockStatementOpt, parameters, properties, c)); return (allFieldsAction, allPropertiesAction); } private (CodeAction fieldAction, CodeAction propertyAction) AddSpecificParameterInitializationActions( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, DocumentOptionSet options) { var field = CreateField(parameter, options, rules); var property = CreateProperty(parameter, options, rules); var fieldAction = new MyCodeAction( string.Format(FeaturesResources.Create_and_assign_field_0, field.Name), c => AddSingleSymbolInitializationAsync(document, constructorDeclaration, blockStatementOpt, parameter, field, c)); var propertyAction = new MyCodeAction( string.Format(FeaturesResources.Create_and_assign_property_0, property.Name), c => AddSingleSymbolInitializationAsync(document, constructorDeclaration, blockStatementOpt, parameter, property, c)); return (fieldAction, propertyAction); } private static ImmutableArray<IParameterSymbol> GetParametersWithoutAssociatedMembers( IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, IMethodSymbol method) { using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var result); foreach (var parameter in method.Parameters) { var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules); if (parameterNameParts.BaseName == "") continue; var assignmentOp = TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt); if (assignmentOp != null) continue; result.Add(parameter); } return result.ToImmutable(); } private ImmutableArray<CodeAction> HandleExistingFieldOrProperty(Document document, IParameterSymbol parameter, SyntaxNode functionDeclaration, IBlockOperation? blockStatementOpt, ISymbol fieldOrProperty) { // Found a field/property that this parameter should be assigned to. // Just offer the simple assignment to it. var resource = fieldOrProperty.Kind == SymbolKind.Field ? FeaturesResources.Initialize_field_0 : FeaturesResources.Initialize_property_0; var title = string.Format(resource, fieldOrProperty.Name); return ImmutableArray.Create<CodeAction>(new MyCodeAction( title, c => AddSingleSymbolInitializationAsync( document, functionDeclaration, blockStatementOpt, parameter, fieldOrProperty, c))); } private static ISymbol? TryFindSiblingFieldOrProperty(IParameterSymbol parameter, IBlockOperation? blockStatementOpt) { foreach (var (siblingParam, _) in GetSiblingParameters(parameter)) { TryFindFieldOrPropertyAssignmentStatement(siblingParam, blockStatementOpt, out var sibling); if (sibling != null) return sibling; } return null; } private IFieldSymbol CreateField( IParameterSymbol parameter, DocumentOptionSet options, ImmutableArray<NamingRule> rules) { var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules).BaseNameParts; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(SymbolKind.Field, Accessibility.Private)) { var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule); var accessibilityLevel = Accessibility.Private; if (requireAccessibilityModifiers.Value is AccessibilityModifiersRequired.Never or AccessibilityModifiersRequired.OmitIfDefault) { var defaultAccessibility = DetermineDefaultFieldAccessibility(parameter.ContainingType); if (defaultAccessibility == Accessibility.Private) { accessibilityLevel = Accessibility.NotApplicable; } } return CodeGenerationSymbolFactory.CreateFieldSymbol( default, accessibilityLevel, DeclarationModifiers.ReadOnly, parameter.Type, uniqueName); } } // We place a special rule in s_builtInRules that matches all fields. So we should // always find a matching rule. throw ExceptionUtilities.Unreachable; } private static string GenerateUniqueName(IParameterSymbol parameter, ImmutableArray<string> parameterNameParts, NamingRule rule) { // Determine an appropriate name to call the new field. var containingType = parameter.ContainingType; var baseName = rule.NamingStyle.CreateName(parameterNameParts); // Ensure that the name is unique in the containing type so we // don't stomp on an existing member. var uniqueName = NameGenerator.GenerateUniqueName( baseName, n => containingType.GetMembers(n).IsEmpty); return uniqueName; } private IPropertySymbol CreateProperty( IParameterSymbol parameter, DocumentOptionSet options, ImmutableArray<NamingRule> rules) { var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules).BaseNameParts; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(SymbolKind.Property, Accessibility.Public)) { var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule); var accessibilityLevel = Accessibility.Public; if (requireAccessibilityModifiers.Value is AccessibilityModifiersRequired.Never or AccessibilityModifiersRequired.OmitIfDefault) { var defaultAccessibility = DetermineDefaultPropertyAccessibility(); if (defaultAccessibility == Accessibility.Public) { accessibilityLevel = Accessibility.NotApplicable; } } var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol( default, Accessibility.Public, default); return CodeGenerationSymbolFactory.CreatePropertySymbol( default, accessibilityLevel, new DeclarationModifiers(), parameter.Type, RefKind.None, explicitInterfaceImplementations: default, name: uniqueName, parameters: default, getMethod: getMethod, setMethod: null); } } // We place a special rule in s_builtInRules that matches all properties. So we should // always find a matching rule. throw ExceptionUtilities.Unreachable; } private async Task<Document> AddAllSymbolInitializationsAsync( Document document, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<ISymbol> fieldsOrProperties, CancellationToken cancellationToken) { Debug.Assert(parameters.Length >= 2); Debug.Assert(fieldsOrProperties.Length > 0); Debug.Assert(parameters.Length == fieldsOrProperties.Length); // Process each param+field/prop in order. Apply the pair to the document getting the updated document. // Then find all the current data in that updated document and move onto the next pair. var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodesToTrack = new List<SyntaxNode> { constructorDeclaration }; if (blockStatementOpt != null) nodesToTrack.Add(blockStatementOpt.Syntax); var trackedRoot = root.TrackNodes(nodesToTrack); var currentDocument = document.WithSyntaxRoot(trackedRoot); for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; var fieldOrProperty = fieldsOrProperties[i]; var currentSemanticModel = await currentDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentCompilation = currentSemanticModel.Compilation; var currentRoot = await currentDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var currentConstructorDeclaration = currentRoot.GetCurrentNode(constructorDeclaration); if (currentConstructorDeclaration == null) continue; IBlockOperation? currentBlockStatementOpt = null; if (blockStatementOpt != null) { currentBlockStatementOpt = (IBlockOperation?)currentSemanticModel.GetOperation(currentRoot.GetCurrentNode(blockStatementOpt.Syntax)!, cancellationToken); if (currentBlockStatementOpt == null) continue; } var currentParameter = (IParameterSymbol?)parameter.GetSymbolKey(cancellationToken).Resolve(currentCompilation, cancellationToken: cancellationToken).GetAnySymbol(); if (currentParameter == null) continue; // fieldOrProperty is a new member. So we don't have to track it to this edit we're making. currentDocument = await AddSingleSymbolInitializationAsync( currentDocument, currentConstructorDeclaration, currentBlockStatementOpt, currentParameter, fieldOrProperty, cancellationToken).ConfigureAwait(false); } return currentDocument; } private async Task<Document> AddSingleSymbolInitializationAsync( Document document, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, IParameterSymbol parameter, ISymbol fieldOrProperty, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, workspace); var generator = editor.Generator; var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (fieldOrProperty.ContainingType == null) { // We're generating a new field/property. Place into the containing type, // ideally before/after a relevant existing member. // First, look for the right containing type (As a type may be partial). // We want the type-block that this constructor is contained within. var typeDeclaration = constructorDeclaration.GetAncestor<TTypeDeclarationSyntax>()!; // Now add the field/property to this type. Use the 'ReplaceNode+callback' form // so that nodes will be appropriate tracked and so we can then update the constructor // below even after we've replaced the whole type with a new type. // // Note: We'll pass the appropriate options so that the new field/property // is appropriate placed before/after an existing field/property. We'll try // to preserve the same order for fields/properties that we have for the constructor // parameters. editor.ReplaceNode( typeDeclaration, (currentTypeDecl, _) => { if (fieldOrProperty is IPropertySymbol property) { return CodeGenerator.AddPropertyDeclaration( currentTypeDecl, property, workspace, GetAddOptions<IPropertySymbol>(parameter, blockStatementOpt, typeDeclaration, options, cancellationToken)); } else if (fieldOrProperty is IFieldSymbol field) { return CodeGenerator.AddFieldDeclaration( currentTypeDecl, field, workspace, GetAddOptions<IFieldSymbol>(parameter, blockStatementOpt, typeDeclaration, options, cancellationToken)); } else { throw ExceptionUtilities.Unreachable; } }); } // Now that we've added any potential members, create an assignment between it // and the parameter. var initializationStatement = (TStatementSyntax)generator.ExpressionStatement( generator.AssignmentStatement( generator.MemberAccessExpression( generator.ThisExpression(), generator.IdentifierName(fieldOrProperty.Name)), generator.IdentifierName(parameter.Name))); // Attempt to place the initialization in a good location in the constructor // We'll want to keep initialization statements in the same order as we see // parameters for the constructor. var statementToAddAfterOpt = TryGetStatementToAddInitializationAfter(parameter, blockStatementOpt); InsertStatement(editor, constructorDeclaration, returnsVoid: true, statementToAddAfterOpt, initializationStatement); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static CodeGenerationOptions GetAddOptions<TSymbol>( IParameterSymbol parameter, IBlockOperation? blockStatementOpt, SyntaxNode typeDeclaration, OptionSet options, CancellationToken cancellationToken) where TSymbol : ISymbol { foreach (var (sibling, before) in GetSiblingParameters(parameter)) { var statement = TryFindFieldOrPropertyAssignmentStatement( sibling, blockStatementOpt, out var fieldOrProperty); if (statement != null && fieldOrProperty is TSymbol symbol) { var symbolSyntax = symbol.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); if (symbolSyntax.Ancestors().Contains(typeDeclaration)) { if (before) { // Found an existing field/property that corresponds to a preceding parameter. // Place ourselves directly after it. return new CodeGenerationOptions(afterThisLocation: symbolSyntax.GetLocation(), options: options); } else { // Found an existing field/property that corresponds to a following parameter. // Place ourselves directly before it. return new CodeGenerationOptions(beforeThisLocation: symbolSyntax.GetLocation(), options: options); } } } } return new CodeGenerationOptions(options: options); } private static ImmutableArray<(IParameterSymbol parameter, bool before)> GetSiblingParameters(IParameterSymbol parameter) { using var _ = ArrayBuilder<(IParameterSymbol, bool before)>.GetInstance(out var siblings); if (parameter.ContainingSymbol is IMethodSymbol method) { var parameterIndex = method.Parameters.IndexOf(parameter); // look for an existing assignment for a parameter that comes before us. // If we find one, we'll add ourselves after that parameter check. for (var i = parameterIndex - 1; i >= 0; i--) siblings.Add((method.Parameters[i], before: true)); // look for an existing check for a parameter that comes before us. // If we find one, we'll add ourselves after that parameter check. for (var i = parameterIndex + 1; i < method.Parameters.Length; i++) siblings.Add((method.Parameters[i], before: false)); } return siblings.ToImmutable(); } private SyntaxNode? TryGetStatementToAddInitializationAfter( IParameterSymbol parameter, IBlockOperation? blockStatementOpt) { // look for an existing assignment for a parameter that comes before/after us. // If we find one, we'll add ourselves before/after that parameter check. foreach (var (sibling, before) in GetSiblingParameters(parameter)) { var statement = TryFindFieldOrPropertyAssignmentStatement(sibling, blockStatementOpt); if (statement != null) { if (before) { return statement.Syntax; } else { var statementIndex = blockStatementOpt!.Operations.IndexOf(statement); return statementIndex > 0 ? blockStatementOpt.Operations[statementIndex - 1].Syntax : null; } } } // We couldn't find a reasonable location for the new initialization statement. // Just place ourselves after the last statement in the constructor. return TryGetLastStatement(blockStatementOpt); } private static IOperation? TryFindFieldOrPropertyAssignmentStatement(IParameterSymbol parameter, IBlockOperation? blockStatementOpt) => TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt, out _); private static IOperation? TryFindFieldOrPropertyAssignmentStatement( IParameterSymbol parameter, IBlockOperation? blockStatementOpt, out ISymbol? fieldOrProperty) { if (blockStatementOpt != null) { var containingType = parameter.ContainingType; foreach (var statement in blockStatementOpt.Operations) { // look for something of the form: "this.s = s" or "this.s = s ?? ..." if (IsFieldOrPropertyAssignment(statement, containingType, out var assignmentExpression, out fieldOrProperty) && IsParameterReferenceOrCoalesceOfParameterReference(assignmentExpression, parameter)) { return statement; } } } fieldOrProperty = null; return null; } private static bool IsParameterReferenceOrCoalesceOfParameterReference( IAssignmentOperation assignmentExpression, IParameterSymbol parameter) { if (IsParameterReference(assignmentExpression.Value, parameter)) { // We already have a member initialized with this parameter like: // this.field = parameter return true; } if (UnwrapImplicitConversion(assignmentExpression.Value) is ICoalesceOperation coalesceExpression && IsParameterReference(coalesceExpression.Value, parameter)) { // We already have a member initialized with this parameter like: // this.field = parameter ?? ... return true; } return false; } private async Task<ISymbol?> TryFindMatchingUninitializedFieldOrPropertySymbolAsync( Document document, IParameterSymbol parameter, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, ImmutableArray<string> parameterWords, CancellationToken cancellationToken) { // Look for a field/property that really looks like it corresponds to this parameter. // Use a variety of heuristics around the name/type to see if this is a match. var containingType = parameter.ContainingType; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); // Walk through the naming rules against this parameter's name to see what // name the user would like for it as a member in this type. Note that we // have some fallback rules that use the standard conventions around // properties /fields so that can still find things even if the user has no // naming preferences set. foreach (var rule in rules) { var memberName = rule.NamingStyle.CreateName(parameterWords); foreach (var memberWithName in containingType.GetMembers(memberName)) { // We found members in our type with that name. If it's a writable // field that we could assign this parameter to, and it's not already // been assigned to, then this field is a good candidate for us to // hook up to. if (memberWithName is IFieldSymbol field && !field.IsConst && IsImplicitConversion(compilation, source: parameter.Type, destination: field.Type) && !ContainsMemberAssignment(blockStatementOpt, field)) { return field; } // If it's a writable property that we could assign this parameter to, and it's // not already been assigned to, then this property is a good candidate for us to // hook up to. if (memberWithName is IPropertySymbol property && property.IsWritableInConstructor() && IsImplicitConversion(compilation, source: parameter.Type, destination: property.Type) && !ContainsMemberAssignment(blockStatementOpt, property)) { return property; } } } // Couldn't find any existing member. Just return nothing so we can offer to // create a member for them. return null; } private static bool ContainsMemberAssignment( IBlockOperation? blockStatementOpt, ISymbol member) { if (blockStatementOpt != null) { foreach (var statement in blockStatementOpt.Operations) { if (IsFieldOrPropertyAssignment(statement, member.ContainingType, out var assignmentExpression) && UnwrapImplicitConversion(assignmentExpression.Target) is IMemberReferenceOperation memberReference && member.Equals(memberReference.Member)) { return true; } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Naming; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InitializeParameter { internal abstract partial class AbstractInitializeMemberFromParameterCodeRefactoringProvider< TTypeDeclarationSyntax, TParameterSyntax, TStatementSyntax, TExpressionSyntax> : AbstractInitializeParameterCodeRefactoringProvider< TTypeDeclarationSyntax, TParameterSyntax, TStatementSyntax, TExpressionSyntax> where TTypeDeclarationSyntax : SyntaxNode where TParameterSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode { protected abstract SyntaxNode TryGetLastStatement(IBlockOperation? blockStatementOpt); protected abstract Accessibility DetermineDefaultFieldAccessibility(INamedTypeSymbol containingType); protected abstract Accessibility DetermineDefaultPropertyAccessibility(); protected override Task<ImmutableArray<CodeAction>> GetRefactoringsForAllParametersAsync( Document document, SyntaxNode functionDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<SyntaxNode> listOfParameterNodes, TextSpan parameterSpan, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<CodeAction>(); } protected override async Task<ImmutableArray<CodeAction>> GetRefactoringsForSingleParameterAsync( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, CancellationToken cancellationToken) { // Only supported for constructor parameters. if (method.MethodKind != MethodKind.Constructor) return ImmutableArray<CodeAction>.Empty; var typeDeclaration = constructorDeclaration.GetAncestor<TTypeDeclarationSyntax>(); if (typeDeclaration == null) return ImmutableArray<CodeAction>.Empty; // See if we're already assigning this parameter to a field/property in this type. If so, there's nothing // more for us to do. var assignmentStatement = TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt); if (assignmentStatement != null) return ImmutableArray<CodeAction>.Empty; // Haven't initialized any fields/properties with this parameter. Offer to assign // to an existing matching field/prop if we can find one, or add a new field/prop // if we can't. var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules); if (parameterNameParts.BaseName == "") return ImmutableArray<CodeAction>.Empty; var fieldOrProperty = await TryFindMatchingUninitializedFieldOrPropertySymbolAsync( document, parameter, blockStatementOpt, rules, parameterNameParts.BaseNameParts, cancellationToken).ConfigureAwait(false); if (fieldOrProperty != null) { return HandleExistingFieldOrProperty( document, parameter, constructorDeclaration, blockStatementOpt, fieldOrProperty); } return await HandleNoExistingFieldOrPropertyAsync( document, parameter, constructorDeclaration, method, blockStatementOpt, rules, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<CodeAction>> HandleNoExistingFieldOrPropertyAsync( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, CancellationToken cancellationToken) { // Didn't find a field/prop that this parameter could be assigned to. // Offer to create new one and assign to that. using var _ = ArrayBuilder<CodeAction>.GetInstance(out var allActions); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var (fieldAction, propertyAction) = AddSpecificParameterInitializationActions( document, parameter, constructorDeclaration, blockStatementOpt, rules, options); // Check if the surrounding parameters are assigned to another field in this class. If so, offer to // make this parameter into a field as well. Otherwise, default to generating a property var siblingFieldOrProperty = TryFindSiblingFieldOrProperty(parameter, blockStatementOpt); if (siblingFieldOrProperty is IFieldSymbol) { allActions.Add(fieldAction); allActions.Add(propertyAction); } else { allActions.Add(propertyAction); allActions.Add(fieldAction); } var (allFieldsAction, allPropertiesAction) = AddAllParameterInitializationActions( document, constructorDeclaration, method, blockStatementOpt, rules, options); if (allFieldsAction != null && allPropertiesAction != null) { if (siblingFieldOrProperty is IFieldSymbol) { allActions.Add(allFieldsAction); allActions.Add(allPropertiesAction); } else { allActions.Add(allPropertiesAction); allActions.Add(allFieldsAction); } } return allActions.ToImmutable(); } private (CodeAction? fieldAction, CodeAction? propertyAction) AddAllParameterInitializationActions( Document document, SyntaxNode constructorDeclaration, IMethodSymbol method, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, DocumentOptionSet options) { if (blockStatementOpt == null) return default; var parameters = GetParametersWithoutAssociatedMembers(blockStatementOpt, rules, method); if (parameters.Length < 2) return default; var fields = parameters.SelectAsArray(p => (ISymbol)CreateField(p, options, rules)); var properties = parameters.SelectAsArray(p => (ISymbol)CreateProperty(p, options, rules)); var allFieldsAction = new MyCodeAction( FeaturesResources.Create_and_assign_remaining_as_fields, c => AddAllSymbolInitializationsAsync( document, constructorDeclaration, blockStatementOpt, parameters, fields, c)); var allPropertiesAction = new MyCodeAction( FeaturesResources.Create_and_assign_remaining_as_properties, c => AddAllSymbolInitializationsAsync( document, constructorDeclaration, blockStatementOpt, parameters, properties, c)); return (allFieldsAction, allPropertiesAction); } private (CodeAction fieldAction, CodeAction propertyAction) AddSpecificParameterInitializationActions( Document document, IParameterSymbol parameter, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, DocumentOptionSet options) { var field = CreateField(parameter, options, rules); var property = CreateProperty(parameter, options, rules); var fieldAction = new MyCodeAction( string.Format(FeaturesResources.Create_and_assign_field_0, field.Name), c => AddSingleSymbolInitializationAsync(document, constructorDeclaration, blockStatementOpt, parameter, field, c)); var propertyAction = new MyCodeAction( string.Format(FeaturesResources.Create_and_assign_property_0, property.Name), c => AddSingleSymbolInitializationAsync(document, constructorDeclaration, blockStatementOpt, parameter, property, c)); return (fieldAction, propertyAction); } private static ImmutableArray<IParameterSymbol> GetParametersWithoutAssociatedMembers( IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, IMethodSymbol method) { using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var result); foreach (var parameter in method.Parameters) { var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules); if (parameterNameParts.BaseName == "") continue; var assignmentOp = TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt); if (assignmentOp != null) continue; result.Add(parameter); } return result.ToImmutable(); } private ImmutableArray<CodeAction> HandleExistingFieldOrProperty(Document document, IParameterSymbol parameter, SyntaxNode functionDeclaration, IBlockOperation? blockStatementOpt, ISymbol fieldOrProperty) { // Found a field/property that this parameter should be assigned to. // Just offer the simple assignment to it. var resource = fieldOrProperty.Kind == SymbolKind.Field ? FeaturesResources.Initialize_field_0 : FeaturesResources.Initialize_property_0; var title = string.Format(resource, fieldOrProperty.Name); return ImmutableArray.Create<CodeAction>(new MyCodeAction( title, c => AddSingleSymbolInitializationAsync( document, functionDeclaration, blockStatementOpt, parameter, fieldOrProperty, c))); } private static ISymbol? TryFindSiblingFieldOrProperty(IParameterSymbol parameter, IBlockOperation? blockStatementOpt) { foreach (var (siblingParam, _) in GetSiblingParameters(parameter)) { TryFindFieldOrPropertyAssignmentStatement(siblingParam, blockStatementOpt, out var sibling); if (sibling != null) return sibling; } return null; } private IFieldSymbol CreateField( IParameterSymbol parameter, DocumentOptionSet options, ImmutableArray<NamingRule> rules) { var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules).BaseNameParts; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(SymbolKind.Field, Accessibility.Private)) { var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule); var accessibilityLevel = Accessibility.Private; if (requireAccessibilityModifiers.Value is AccessibilityModifiersRequired.Never or AccessibilityModifiersRequired.OmitIfDefault) { var defaultAccessibility = DetermineDefaultFieldAccessibility(parameter.ContainingType); if (defaultAccessibility == Accessibility.Private) { accessibilityLevel = Accessibility.NotApplicable; } } return CodeGenerationSymbolFactory.CreateFieldSymbol( default, accessibilityLevel, DeclarationModifiers.ReadOnly, parameter.Type, uniqueName); } } // We place a special rule in s_builtInRules that matches all fields. So we should // always find a matching rule. throw ExceptionUtilities.Unreachable; } private static string GenerateUniqueName(IParameterSymbol parameter, ImmutableArray<string> parameterNameParts, NamingRule rule) { // Determine an appropriate name to call the new field. var containingType = parameter.ContainingType; var baseName = rule.NamingStyle.CreateName(parameterNameParts); // Ensure that the name is unique in the containing type so we // don't stomp on an existing member. var uniqueName = NameGenerator.GenerateUniqueName( baseName, n => containingType.GetMembers(n).IsEmpty); return uniqueName; } private IPropertySymbol CreateProperty( IParameterSymbol parameter, DocumentOptionSet options, ImmutableArray<NamingRule> rules) { var requireAccessibilityModifiers = options.GetOption(CodeStyleOptions2.RequireAccessibilityModifiers); var parameterNameParts = IdentifierNameParts.CreateIdentifierNameParts(parameter, rules).BaseNameParts; foreach (var rule in rules) { if (rule.SymbolSpecification.AppliesTo(SymbolKind.Property, Accessibility.Public)) { var uniqueName = GenerateUniqueName(parameter, parameterNameParts, rule); var accessibilityLevel = Accessibility.Public; if (requireAccessibilityModifiers.Value is AccessibilityModifiersRequired.Never or AccessibilityModifiersRequired.OmitIfDefault) { var defaultAccessibility = DetermineDefaultPropertyAccessibility(); if (defaultAccessibility == Accessibility.Public) { accessibilityLevel = Accessibility.NotApplicable; } } var getMethod = CodeGenerationSymbolFactory.CreateAccessorSymbol( default, Accessibility.Public, default); return CodeGenerationSymbolFactory.CreatePropertySymbol( default, accessibilityLevel, new DeclarationModifiers(), parameter.Type, RefKind.None, explicitInterfaceImplementations: default, name: uniqueName, parameters: default, getMethod: getMethod, setMethod: null); } } // We place a special rule in s_builtInRules that matches all properties. So we should // always find a matching rule. throw ExceptionUtilities.Unreachable; } private async Task<Document> AddAllSymbolInitializationsAsync( Document document, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<ISymbol> fieldsOrProperties, CancellationToken cancellationToken) { Debug.Assert(parameters.Length >= 2); Debug.Assert(fieldsOrProperties.Length > 0); Debug.Assert(parameters.Length == fieldsOrProperties.Length); // Process each param+field/prop in order. Apply the pair to the document getting the updated document. // Then find all the current data in that updated document and move onto the next pair. var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var nodesToTrack = new List<SyntaxNode> { constructorDeclaration }; if (blockStatementOpt != null) nodesToTrack.Add(blockStatementOpt.Syntax); var trackedRoot = root.TrackNodes(nodesToTrack); var currentDocument = document.WithSyntaxRoot(trackedRoot); for (var i = 0; i < parameters.Length; i++) { var parameter = parameters[i]; var fieldOrProperty = fieldsOrProperties[i]; var currentSemanticModel = await currentDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentCompilation = currentSemanticModel.Compilation; var currentRoot = await currentDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var currentConstructorDeclaration = currentRoot.GetCurrentNode(constructorDeclaration); if (currentConstructorDeclaration == null) continue; IBlockOperation? currentBlockStatementOpt = null; if (blockStatementOpt != null) { currentBlockStatementOpt = (IBlockOperation?)currentSemanticModel.GetOperation(currentRoot.GetCurrentNode(blockStatementOpt.Syntax)!, cancellationToken); if (currentBlockStatementOpt == null) continue; } var currentParameter = (IParameterSymbol?)parameter.GetSymbolKey(cancellationToken).Resolve(currentCompilation, cancellationToken: cancellationToken).GetAnySymbol(); if (currentParameter == null) continue; // fieldOrProperty is a new member. So we don't have to track it to this edit we're making. currentDocument = await AddSingleSymbolInitializationAsync( currentDocument, currentConstructorDeclaration, currentBlockStatementOpt, currentParameter, fieldOrProperty, cancellationToken).ConfigureAwait(false); } return currentDocument; } private async Task<Document> AddSingleSymbolInitializationAsync( Document document, SyntaxNode constructorDeclaration, IBlockOperation? blockStatementOpt, IParameterSymbol parameter, ISymbol fieldOrProperty, CancellationToken cancellationToken) { var workspace = document.Project.Solution.Workspace; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, workspace); var generator = editor.Generator; var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); if (fieldOrProperty.ContainingType == null) { // We're generating a new field/property. Place into the containing type, // ideally before/after a relevant existing member. // First, look for the right containing type (As a type may be partial). // We want the type-block that this constructor is contained within. var typeDeclaration = constructorDeclaration.GetAncestor<TTypeDeclarationSyntax>()!; // Now add the field/property to this type. Use the 'ReplaceNode+callback' form // so that nodes will be appropriate tracked and so we can then update the constructor // below even after we've replaced the whole type with a new type. // // Note: We'll pass the appropriate options so that the new field/property // is appropriate placed before/after an existing field/property. We'll try // to preserve the same order for fields/properties that we have for the constructor // parameters. editor.ReplaceNode( typeDeclaration, (currentTypeDecl, _) => { if (fieldOrProperty is IPropertySymbol property) { return CodeGenerator.AddPropertyDeclaration( currentTypeDecl, property, workspace, GetAddOptions<IPropertySymbol>(parameter, blockStatementOpt, typeDeclaration, options, cancellationToken)); } else if (fieldOrProperty is IFieldSymbol field) { return CodeGenerator.AddFieldDeclaration( currentTypeDecl, field, workspace, GetAddOptions<IFieldSymbol>(parameter, blockStatementOpt, typeDeclaration, options, cancellationToken)); } else { throw ExceptionUtilities.Unreachable; } }); } // Now that we've added any potential members, create an assignment between it // and the parameter. var initializationStatement = (TStatementSyntax)generator.ExpressionStatement( generator.AssignmentStatement( generator.MemberAccessExpression( generator.ThisExpression(), generator.IdentifierName(fieldOrProperty.Name)), generator.IdentifierName(parameter.Name))); // Attempt to place the initialization in a good location in the constructor // We'll want to keep initialization statements in the same order as we see // parameters for the constructor. var statementToAddAfterOpt = TryGetStatementToAddInitializationAfter(parameter, blockStatementOpt); InsertStatement(editor, constructorDeclaration, returnsVoid: true, statementToAddAfterOpt, initializationStatement); return document.WithSyntaxRoot(editor.GetChangedRoot()); } private static CodeGenerationOptions GetAddOptions<TSymbol>( IParameterSymbol parameter, IBlockOperation? blockStatementOpt, SyntaxNode typeDeclaration, OptionSet options, CancellationToken cancellationToken) where TSymbol : ISymbol { foreach (var (sibling, before) in GetSiblingParameters(parameter)) { var statement = TryFindFieldOrPropertyAssignmentStatement( sibling, blockStatementOpt, out var fieldOrProperty); if (statement != null && fieldOrProperty is TSymbol symbol) { var symbolSyntax = symbol.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); if (symbolSyntax.Ancestors().Contains(typeDeclaration)) { if (before) { // Found an existing field/property that corresponds to a preceding parameter. // Place ourselves directly after it. return new CodeGenerationOptions(afterThisLocation: symbolSyntax.GetLocation(), options: options); } else { // Found an existing field/property that corresponds to a following parameter. // Place ourselves directly before it. return new CodeGenerationOptions(beforeThisLocation: symbolSyntax.GetLocation(), options: options); } } } } return new CodeGenerationOptions(options: options); } private static ImmutableArray<(IParameterSymbol parameter, bool before)> GetSiblingParameters(IParameterSymbol parameter) { using var _ = ArrayBuilder<(IParameterSymbol, bool before)>.GetInstance(out var siblings); if (parameter.ContainingSymbol is IMethodSymbol method) { var parameterIndex = method.Parameters.IndexOf(parameter); // look for an existing assignment for a parameter that comes before us. // If we find one, we'll add ourselves after that parameter check. for (var i = parameterIndex - 1; i >= 0; i--) siblings.Add((method.Parameters[i], before: true)); // look for an existing check for a parameter that comes before us. // If we find one, we'll add ourselves after that parameter check. for (var i = parameterIndex + 1; i < method.Parameters.Length; i++) siblings.Add((method.Parameters[i], before: false)); } return siblings.ToImmutable(); } private SyntaxNode? TryGetStatementToAddInitializationAfter( IParameterSymbol parameter, IBlockOperation? blockStatementOpt) { // look for an existing assignment for a parameter that comes before/after us. // If we find one, we'll add ourselves before/after that parameter check. foreach (var (sibling, before) in GetSiblingParameters(parameter)) { var statement = TryFindFieldOrPropertyAssignmentStatement(sibling, blockStatementOpt); if (statement != null) { if (before) { return statement.Syntax; } else { var statementIndex = blockStatementOpt!.Operations.IndexOf(statement); return statementIndex > 0 ? blockStatementOpt.Operations[statementIndex - 1].Syntax : null; } } } // We couldn't find a reasonable location for the new initialization statement. // Just place ourselves after the last statement in the constructor. return TryGetLastStatement(blockStatementOpt); } private static IOperation? TryFindFieldOrPropertyAssignmentStatement(IParameterSymbol parameter, IBlockOperation? blockStatementOpt) => TryFindFieldOrPropertyAssignmentStatement(parameter, blockStatementOpt, out _); private static IOperation? TryFindFieldOrPropertyAssignmentStatement( IParameterSymbol parameter, IBlockOperation? blockStatementOpt, out ISymbol? fieldOrProperty) { if (blockStatementOpt != null) { var containingType = parameter.ContainingType; foreach (var statement in blockStatementOpt.Operations) { // look for something of the form: "this.s = s" or "this.s = s ?? ..." if (IsFieldOrPropertyAssignment(statement, containingType, out var assignmentExpression, out fieldOrProperty) && IsParameterReferenceOrCoalesceOfParameterReference(assignmentExpression, parameter)) { return statement; } } } fieldOrProperty = null; return null; } private static bool IsParameterReferenceOrCoalesceOfParameterReference( IAssignmentOperation assignmentExpression, IParameterSymbol parameter) { if (IsParameterReference(assignmentExpression.Value, parameter)) { // We already have a member initialized with this parameter like: // this.field = parameter return true; } if (UnwrapImplicitConversion(assignmentExpression.Value) is ICoalesceOperation coalesceExpression && IsParameterReference(coalesceExpression.Value, parameter)) { // We already have a member initialized with this parameter like: // this.field = parameter ?? ... return true; } return false; } private async Task<ISymbol?> TryFindMatchingUninitializedFieldOrPropertySymbolAsync( Document document, IParameterSymbol parameter, IBlockOperation? blockStatementOpt, ImmutableArray<NamingRule> rules, ImmutableArray<string> parameterWords, CancellationToken cancellationToken) { // Look for a field/property that really looks like it corresponds to this parameter. // Use a variety of heuristics around the name/type to see if this is a match. var containingType = parameter.ContainingType; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); // Walk through the naming rules against this parameter's name to see what // name the user would like for it as a member in this type. Note that we // have some fallback rules that use the standard conventions around // properties /fields so that can still find things even if the user has no // naming preferences set. foreach (var rule in rules) { var memberName = rule.NamingStyle.CreateName(parameterWords); foreach (var memberWithName in containingType.GetMembers(memberName)) { // We found members in our type with that name. If it's a writable // field that we could assign this parameter to, and it's not already // been assigned to, then this field is a good candidate for us to // hook up to. if (memberWithName is IFieldSymbol field && !field.IsConst && IsImplicitConversion(compilation, source: parameter.Type, destination: field.Type) && !ContainsMemberAssignment(blockStatementOpt, field)) { return field; } // If it's a writable property that we could assign this parameter to, and it's // not already been assigned to, then this property is a good candidate for us to // hook up to. if (memberWithName is IPropertySymbol property && property.IsWritableInConstructor() && IsImplicitConversion(compilation, source: parameter.Type, destination: property.Type) && !ContainsMemberAssignment(blockStatementOpt, property)) { return property; } } } // Couldn't find any existing member. Just return nothing so we can offer to // create a member for them. return null; } private static bool ContainsMemberAssignment( IBlockOperation? blockStatementOpt, ISymbol member) { if (blockStatementOpt != null) { foreach (var statement in blockStatementOpt.Operations) { if (IsFieldOrPropertyAssignment(statement, member.ContainingType, out var assignmentExpression) && UnwrapImplicitConversion(assignmentExpression.Target) is IMemberReferenceOperation memberReference && member.Equals(memberReference.Member)) { return true; } } } return false; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/InterfaceImplementationCallFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class InterfaceImplementationCallFinder : AbstractCallFinder { private readonly string _text; public InterfaceImplementationCallFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { _text = string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, symbol.ToDisplayString()); } public override string DisplayName => _text; public override string SearchCategory => CallHierarchyPredefinedSearchCategoryNames.InterfaceImplementations; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return calls.Where(c => c.IsDirect); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class InterfaceImplementationCallFinder : AbstractCallFinder { private readonly string _text; public InterfaceImplementationCallFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { _text = string.Format(EditorFeaturesResources.Calls_To_Interface_Implementation_0, symbol.ToDisplayString()); } public override string DisplayName => _text; public override string SearchCategory => CallHierarchyPredefinedSearchCategoryNames.InterfaceImplementations; protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return calls.Where(c => c.IsDirect); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/Test/CodeGeneration/ExpressionPrecedenceGenerationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [Trait(Traits.Feature, Traits.Features.CodeGeneration)] public class ExpressionPrecedenceGenerationTests : AbstractCodeGenerationTests { [Fact] public void TestAddMultiplyPrecedence1() { Test( f => f.MultiplyExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) + (2)) * (3)", csSimple: "(1 + 2) * 3", vb: "((1) + (2)) * (3)", vbSimple: "(1 + 2) * 3"); } [Fact] public void TestAddMultiplyPrecedence2() { Test( f => f.AddExpression( f.MultiplyExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) * (2)) + (3)", csSimple: "1 * 2 + 3", vb: "((1) * (2)) + (3)", vbSimple: "1 * 2 + 3"); } [Fact] public void TestAddMultiplyPrecedence3() { Test( f => f.MultiplyExpression( f.LiteralExpression(1), f.AddExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) * ((2) + (3))", csSimple: "1 * (2 + 3)", vb: "(1) * ((2) + (3))", vbSimple: "1 * (2 + 3)"); } [Fact] public void TestAddMultiplyPrecedence4() { Test( f => f.AddExpression( f.LiteralExpression(1), f.MultiplyExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) + ((2) * (3))", csSimple: "1 + 2 * 3", vb: "(1) + ((2) * (3))", vbSimple: "1 + 2 * 3"); } [Fact] public void TestBitwiseAndOrPrecedence1() { Test( f => f.BitwiseAndExpression( f.BitwiseOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) | (2)) & (3)", csSimple: "(1 | 2) & 3", vb: "((1) Or (2)) And (3)", vbSimple: "(1 Or 2) And 3"); } [Fact] public void TestBitwiseAndOrPrecedence2() { Test( f => f.BitwiseOrExpression( f.BitwiseAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) & (2)) | (3)", csSimple: "1 & 2 | 3", vb: "((1) And (2)) Or (3)", vbSimple: "1 And 2 Or 3"); } [Fact] public void TestBitwiseAndOrPrecedence3() { Test( f => f.BitwiseAndExpression( f.LiteralExpression(1), f.BitwiseOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) & ((2) | (3))", csSimple: "1 & (2 | 3)", vb: "(1) And ((2) Or (3))", vbSimple: "1 And (2 Or 3)"); } [Fact] public void TestBitwiseAndOrPrecedence4() { Test( f => f.BitwiseOrExpression( f.LiteralExpression(1), f.BitwiseAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) | ((2) & (3))", csSimple: "1 | 2 & 3", vb: "(1) Or ((2) And (3))", vbSimple: "1 Or 2 And 3"); } [Fact] public void TestLogicalAndOrPrecedence1() { Test( f => f.LogicalAndExpression( f.LogicalOrExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) || (2)) && (3)", csSimple: "(1 || 2) && 3", vb: "((1) OrElse (2)) AndAlso (3)", vbSimple: "(1 OrElse 2) AndAlso 3"); } [Fact] public void TestLogicalAndOrPrecedence2() { Test( f => f.LogicalOrExpression( f.LogicalAndExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.LiteralExpression(3)), cs: "((1) && (2)) || (3)", csSimple: "1 && 2 || 3", vb: "((1) AndAlso (2)) OrElse (3)", vbSimple: "1 AndAlso 2 OrElse 3"); } [Fact] public void TestLogicalAndOrPrecedence3() { Test( f => f.LogicalAndExpression( f.LiteralExpression(1), f.LogicalOrExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) && ((2) || (3))", csSimple: "1 && (2 || 3)", vb: "(1) AndAlso ((2) OrElse (3))", vbSimple: "1 AndAlso (2 OrElse 3)"); } [Fact] public void TestLogicalAndOrPrecedence4() { Test( f => f.LogicalOrExpression( f.LiteralExpression(1), f.LogicalAndExpression( f.LiteralExpression(2), f.LiteralExpression(3))), cs: "(1) || ((2) && (3))", csSimple: "1 || 2 && 3", vb: "(1) OrElse ((2) AndAlso (3))", vbSimple: "1 OrElse 2 AndAlso 3"); } [Fact] public void TestMemberAccessOffOfAdd1() { Test( f => f.MemberAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.IdentifierName("M")), cs: "((1) + (2)).M", csSimple: "(1 + 2).M", vb: "((1) + (2)).M", vbSimple: "(1 + 2).M"); } [Fact] public void TestConditionalExpression1() { Test( f => f.ConditionalExpression( f.AssignmentStatement( f.IdentifierName("E1"), f.IdentifierName("E2")), f.IdentifierName("T"), f.IdentifierName("F")), cs: "(E1 = (E2)) ? (T) : (F)", csSimple: "(E1 = E2) ? T : F", vb: null, vbSimple: null); } [Fact] public void TestConditionalExpression2() { Test( f => f.AddExpression( f.ConditionalExpression( f.IdentifierName("E1"), f.IdentifierName("T1"), f.IdentifierName("F1")), f.ConditionalExpression( f.IdentifierName("E2"), f.IdentifierName("T2"), f.IdentifierName("F2"))), cs: "((E1) ? (T1) : (F1)) + ((E2) ? (T2) : (F2))", csSimple: "(E1 ? T1 : F1) + (E2 ? T2 : F2)", vb: null, vbSimple: null); } [Fact] public void TestMemberAccessOffOfElementAccess() { Test( f => f.ElementAccessExpression( f.AddExpression( f.LiteralExpression(1), f.LiteralExpression(2)), f.Argument(f.IdentifierName("M"))), cs: "((1) + (2))[M]", csSimple: "(1 + 2)[M]", vb: "((1) + (2))(M)", vbSimple: "(1 + 2)(M)"); } [Fact] public void TestMemberAccessOffOfIsExpression() { Test( f => f.MemberAccessExpression( f.IsTypeExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) is SomeType).M", csSimple: "(a is SomeType).M", vb: "(TypeOf (a) Is SomeType).M", vbSimple: "(TypeOf a Is SomeType).M"); } [Fact] public void TestIsOfMemberAccessExpression() { Test( f => f.IsTypeExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) is SomeType", csSimple: "a.M is SomeType", vb: "TypeOf (a.M) Is SomeType", vbSimple: "TypeOf a.M Is SomeType"); } [Fact] public void TestMemberAccessOffOfAsExpression() { Test( f => f.MemberAccessExpression( f.TryCastExpression( f.IdentifierName("a"), CreateClass("SomeType")), f.IdentifierName("M")), cs: "((a) as SomeType).M", csSimple: "(a as SomeType).M", vb: "(TryCast(a, SomeType)).M", vbSimple: "TryCast(a, SomeType).M"); } [Fact] public void TestAsOfMemberAccessExpression() { Test( f => f.TryCastExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M")), CreateClass("SomeType")), cs: "(a.M) as SomeType", csSimple: "a.M as SomeType", vb: "TryCast(a.M, SomeType)", vbSimple: "TryCast(a.M, SomeType)"); } [Fact] public void TestMemberAccessOffOfNotExpression() { Test( f => f.MemberAccessExpression( f.LogicalNotExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(!(a)).M", csSimple: "(!a).M", vb: "(Not (a)).M", vbSimple: "(Not a).M"); } [Fact] public void TestNotOfMemberAccessExpression() { Test( f => f.LogicalNotExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "!(a.M)", csSimple: "!a.M", vb: "Not (a.M)", vbSimple: "Not a.M"); } [Fact] public void TestMemberAccessOffOfCastExpression() { Test( f => f.MemberAccessExpression( f.CastExpression( CreateClass("SomeType"), f.IdentifierName("a")), f.IdentifierName("M")), cs: "((SomeType)(a)).M", csSimple: "((SomeType)a).M", vb: "(DirectCast(a, SomeType)).M", vbSimple: "DirectCast(a, SomeType).M"); } [Fact] public void TestCastOfAddExpression() { Test( f => f.CastExpression( CreateClass("SomeType"), f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "(SomeType)((a) + (b))", csSimple: "(SomeType)(a + b)", vb: "DirectCast((a) + (b), SomeType)", vbSimple: "DirectCast(a + b, SomeType)"); } [Fact] public void TestNegateOfAddExpression() { Test( f => f.NegateExpression( f.AddExpression( f.IdentifierName("a"), f.IdentifierName("b"))), cs: "-((a) + (b))", csSimple: "-(a + b)", vb: "-((a) + (b))", vbSimple: "-(a + b)"); } [Fact] public void TestMemberAccessOffOfNegate() { Test( f => f.MemberAccessExpression( f.NegateExpression( f.IdentifierName("a")), f.IdentifierName("M")), cs: "(-(a)).M", csSimple: "(-a).M", vb: "(-(a)).M", vbSimple: "(-a).M"); } [Fact] public void TestNegateOfMemberAccess() { Test(f => f.NegateExpression( f.MemberAccessExpression( f.IdentifierName("a"), f.IdentifierName("M"))), cs: "-(a.M)", csSimple: "-a.M", vb: "-(a.M)", vbSimple: "-a.M"); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.StateManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// This is in charge of anything related to <see cref="StateSet"/> /// </summary> private partial class StateManager { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; /// <summary> /// Analyzers supplied by the host (IDE). These are built-in to the IDE, the compiler, or from an installed IDE extension (VSIX). /// Maps language name to the analyzers and their state. /// </summary> private ImmutableDictionary<string, HostAnalyzerStateSets> _hostAnalyzerStateMap; /// <summary> /// Analyzers referenced by the project via a PackageReference. /// </summary> private readonly ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets> _projectAnalyzerStateMap; /// <summary> /// This will be raised whenever <see cref="StateManager"/> finds <see cref="Project.AnalyzerReferences"/> change /// </summary> public event EventHandler<ProjectAnalyzerReferenceChangedEventArgs>? ProjectAnalyzerReferenceChanged; public StateManager(DiagnosticAnalyzerInfoCache analyzerInfoCache) { _analyzerInfoCache = analyzerInfoCache; _hostAnalyzerStateMap = ImmutableDictionary<string, HostAnalyzerStateSets>.Empty; _projectAnalyzerStateMap = new ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets>(concurrencyLevel: 2, capacity: 10); } /// <summary> /// Return all <see cref="StateSet"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetAllStateSets() => GetAllHostStateSets().Concat(GetAllProjectStateSets()); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="ProjectId"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetStateSets(ProjectId projectId) { var hostStateSets = GetAllHostStateSets(); return _projectAnalyzerStateMap.TryGetValue(projectId, out var entry) ? hostStateSets.Concat(entry.StateSetMap.Values) : hostStateSets; } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// Difference with <see cref="GetStateSets(ProjectId)"/> is that /// this will only return <see cref="StateSet"/>s that have same language as <paramref name="project"/>. /// </summary> public IEnumerable<StateSet> GetStateSets(Project project) => GetStateSets(project.Id).Where(s => s.Language == project.Language); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/> and update internal state. /// /// since this has a side-effect, this should never be called concurrently. and incremental analyzer (solution crawler) should guarantee that. /// </summary> public IEnumerable<StateSet> GetOrUpdateStateSets(Project project) { var projectStateSets = GetOrUpdateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/>. /// Unlike <see cref="GetOrUpdateStateSets(Project)"/>, this has no side effect. /// </summary> public IEnumerable<StateSet> GetOrCreateStateSets(Project project) { var projectStateSets = GetOrCreateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/> for the given <see cref="DiagnosticAnalyzer"/> in the context of <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/> for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/> for the <see cref="Project"/>. /// This will not have any side effect. /// </summary> public StateSet? GetOrCreateStateSet(Project project, DiagnosticAnalyzer analyzer) { var projectStateSets = GetOrCreateProjectStateSets(project); if (projectStateSets.StateSetMap.TryGetValue(analyzer, out var stateSet)) { return stateSet; } var hostStateSetMap = GetOrCreateHostStateSets(project, projectStateSets).StateSetMap; if (hostStateSetMap.TryGetValue(analyzer, out stateSet)) { return stateSet; } return null; } /// <summary> /// Return <see cref="StateSet"/>s that are added as the given <see cref="Project"/>'s AnalyzerReferences. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public ImmutableArray<StateSet> CreateBuildOnlyProjectStateSet(Project project) { var projectStateSets = project.SupportsCompilation ? GetOrUpdateProjectStateSets(project) : ProjectAnalyzerStateSets.Default; var hostStateSets = GetOrCreateHostStateSets(project, projectStateSets); if (!project.SupportsCompilation) { // languages which don't use our compilation model but diagnostic framework, // all their analyzer should be host analyzers. return all host analyzers // for the language return hostStateSets.OrderedStateSets; } var hostStateSetMap = hostStateSets.StateSetMap; // create project analyzer reference identity map var projectAnalyzerReferenceIds = project.AnalyzerReferences.Select(r => r.Id).ToSet(); // create build only stateSet array var stateSets = ImmutableArray.CreateBuilder<StateSet>(); // include compiler analyzer in build only state, if available StateSet? compilerStateSet = null; var hostAnalyzers = project.Solution.State.Analyzers; var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null && hostStateSetMap.TryGetValue(compilerAnalyzer, out compilerStateSet)) { stateSets.Add(compilerStateSet); } // now add all project analyzers stateSets.AddRange(projectStateSets.StateSetMap.Values); // now add analyzers that exist in both host and project var hostAnalyzersById = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); foreach (var (identity, analyzers) in hostAnalyzersById) { if (!projectAnalyzerReferenceIds.Contains(identity)) { // it is from host analyzer package rather than project analyzer reference // which build doesn't have continue; } // if same analyzer exists both in host (vsix) and in analyzer reference, // we include it in build only analyzer. foreach (var analyzer in analyzers) { if (hostStateSetMap.TryGetValue(analyzer, out var stateSet) && stateSet != compilerStateSet) { stateSets.Add(stateSet); } } } return stateSets.ToImmutable(); } /// <summary> /// Determines if any of the state sets in <see cref="GetAllHostStateSets()"/> match a specified predicate. /// </summary> /// <remarks> /// This method avoids the performance overhead of calling <see cref="GetAllHostStateSets()"/> for the /// specific case where the result is only used for testing if any element meets certain conditions. /// </remarks> public bool HasAnyHostStateSet<TArg>(Func<StateSet, TArg, bool> match, TArg arg) { foreach (var (_, hostStateSet) in _hostAnalyzerStateMap) { foreach (var stateSet in hostStateSet.OrderedStateSets) { if (match(stateSet, arg)) return true; } } return false; } /// <summary> /// Determines if any of the state sets in <see cref="_projectAnalyzerStateMap"/> for a specific project /// match a specified predicate. /// </summary> /// <remarks> /// <para>This method avoids the performance overhead of calling <see cref="GetStateSets(Project)"/> for the /// specific case where the result is only used for testing if any element meets certain conditions.</para> /// /// <para>Note that host state sets (i.e. ones retured by <see cref="GetAllHostStateSets()"/> are not tested /// by this method.</para> /// </remarks> public bool HasAnyProjectStateSet<TArg>(ProjectId projectId, Func<StateSet, TArg, bool> match, TArg arg) { if (_projectAnalyzerStateMap.TryGetValue(projectId, out var entry)) { foreach (var (_, stateSet) in entry.StateSetMap) { if (match(stateSet, arg)) return true; } } return false; } public bool OnProjectRemoved(IEnumerable<StateSet> stateSets, ProjectId projectId) { var removed = false; foreach (var stateSet in stateSets) { removed |= stateSet.OnProjectRemoved(projectId); } _projectAnalyzerStateMap.TryRemove(projectId, out _); return removed; } private void RaiseProjectAnalyzerReferenceChanged(ProjectAnalyzerReferenceChangedEventArgs args) => ProjectAnalyzerReferenceChanged?.Invoke(this, args); private static ImmutableDictionary<DiagnosticAnalyzer, StateSet> CreateStateSetMap( string language, IEnumerable<ImmutableArray<DiagnosticAnalyzer>> analyzerCollection, bool includeFileContentLoadAnalyzer) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, StateSet>(); if (includeFileContentLoadAnalyzer) { builder.Add(FileContentLoadAnalyzer.Instance, new StateSet(language, FileContentLoadAnalyzer.Instance, PredefinedBuildTools.Live)); } foreach (var analyzers in analyzerCollection) { foreach (var analyzer in analyzers) { Debug.Assert(analyzer != FileContentLoadAnalyzer.Instance); // TODO: // #1, all de-duplication should move to DiagnosticAnalyzerInfoCache // #2, not sure whether de-duplication of analyzer itself makes sense. this can only happen // if user deliberately put same analyzer twice. if (builder.ContainsKey(analyzer)) { continue; } var buildToolName = analyzer.IsBuiltInAnalyzer() ? PredefinedBuildTools.Live : analyzer.GetAnalyzerAssemblyName(); builder.Add(analyzer, new StateSet(language, analyzer, buildToolName)); } } return builder.ToImmutable(); } [Conditional("DEBUG")] private static void VerifyUniqueStateNames(IEnumerable<StateSet> stateSets) { // Ensure diagnostic state name is indeed unique. var set = new HashSet<ValueTuple<string, string>>(); foreach (var stateSet in stateSets) { Contract.ThrowIfFalse(set.Add((stateSet.Language, stateSet.StateName))); } } [Conditional("DEBUG")] private void VerifyProjectDiagnosticStates(IEnumerable<StateSet> stateSets) { // We do not de-duplicate analyzer instances across host and project analyzers. var projectAnalyzers = stateSets.Select(state => state.Analyzer).ToImmutableHashSet(); var hostStates = GetAllHostStateSets().Where(state => !projectAnalyzers.Contains(state.Analyzer)); VerifyUniqueStateNames(hostStates.Concat(stateSets)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// This is in charge of anything related to <see cref="StateSet"/> /// </summary> private partial class StateManager { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; /// <summary> /// Analyzers supplied by the host (IDE). These are built-in to the IDE, the compiler, or from an installed IDE extension (VSIX). /// Maps language name to the analyzers and their state. /// </summary> private ImmutableDictionary<string, HostAnalyzerStateSets> _hostAnalyzerStateMap; /// <summary> /// Analyzers referenced by the project via a PackageReference. /// </summary> private readonly ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets> _projectAnalyzerStateMap; /// <summary> /// This will be raised whenever <see cref="StateManager"/> finds <see cref="Project.AnalyzerReferences"/> change /// </summary> public event EventHandler<ProjectAnalyzerReferenceChangedEventArgs>? ProjectAnalyzerReferenceChanged; public StateManager(DiagnosticAnalyzerInfoCache analyzerInfoCache) { _analyzerInfoCache = analyzerInfoCache; _hostAnalyzerStateMap = ImmutableDictionary<string, HostAnalyzerStateSets>.Empty; _projectAnalyzerStateMap = new ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets>(concurrencyLevel: 2, capacity: 10); } /// <summary> /// Return all <see cref="StateSet"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetAllStateSets() => GetAllHostStateSets().Concat(GetAllProjectStateSets()); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="ProjectId"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetStateSets(ProjectId projectId) { var hostStateSets = GetAllHostStateSets(); return _projectAnalyzerStateMap.TryGetValue(projectId, out var entry) ? hostStateSets.Concat(entry.StateSetMap.Values) : hostStateSets; } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// Difference with <see cref="GetStateSets(ProjectId)"/> is that /// this will only return <see cref="StateSet"/>s that have same language as <paramref name="project"/>. /// </summary> public IEnumerable<StateSet> GetStateSets(Project project) => GetStateSets(project.Id).Where(s => s.Language == project.Language); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/> and update internal state. /// /// since this has a side-effect, this should never be called concurrently. and incremental analyzer (solution crawler) should guarantee that. /// </summary> public IEnumerable<StateSet> GetOrUpdateStateSets(Project project) { var projectStateSets = GetOrUpdateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/>. /// Unlike <see cref="GetOrUpdateStateSets(Project)"/>, this has no side effect. /// </summary> public IEnumerable<StateSet> GetOrCreateStateSets(Project project) { var projectStateSets = GetOrCreateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/> for the given <see cref="DiagnosticAnalyzer"/> in the context of <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/> for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/> for the <see cref="Project"/>. /// This will not have any side effect. /// </summary> public StateSet? GetOrCreateStateSet(Project project, DiagnosticAnalyzer analyzer) { var projectStateSets = GetOrCreateProjectStateSets(project); if (projectStateSets.StateSetMap.TryGetValue(analyzer, out var stateSet)) { return stateSet; } var hostStateSetMap = GetOrCreateHostStateSets(project, projectStateSets).StateSetMap; if (hostStateSetMap.TryGetValue(analyzer, out stateSet)) { return stateSet; } return null; } /// <summary> /// Return <see cref="StateSet"/>s that are added as the given <see cref="Project"/>'s AnalyzerReferences. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public ImmutableArray<StateSet> CreateBuildOnlyProjectStateSet(Project project) { var projectStateSets = project.SupportsCompilation ? GetOrUpdateProjectStateSets(project) : ProjectAnalyzerStateSets.Default; var hostStateSets = GetOrCreateHostStateSets(project, projectStateSets); if (!project.SupportsCompilation) { // languages which don't use our compilation model but diagnostic framework, // all their analyzer should be host analyzers. return all host analyzers // for the language return hostStateSets.OrderedStateSets; } var hostStateSetMap = hostStateSets.StateSetMap; // create project analyzer reference identity map var projectAnalyzerReferenceIds = project.AnalyzerReferences.Select(r => r.Id).ToSet(); // create build only stateSet array var stateSets = ImmutableArray.CreateBuilder<StateSet>(); // include compiler analyzer in build only state, if available StateSet? compilerStateSet = null; var hostAnalyzers = project.Solution.State.Analyzers; var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null && hostStateSetMap.TryGetValue(compilerAnalyzer, out compilerStateSet)) { stateSets.Add(compilerStateSet); } // now add all project analyzers stateSets.AddRange(projectStateSets.StateSetMap.Values); // now add analyzers that exist in both host and project var hostAnalyzersById = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); foreach (var (identity, analyzers) in hostAnalyzersById) { if (!projectAnalyzerReferenceIds.Contains(identity)) { // it is from host analyzer package rather than project analyzer reference // which build doesn't have continue; } // if same analyzer exists both in host (vsix) and in analyzer reference, // we include it in build only analyzer. foreach (var analyzer in analyzers) { if (hostStateSetMap.TryGetValue(analyzer, out var stateSet) && stateSet != compilerStateSet) { stateSets.Add(stateSet); } } } return stateSets.ToImmutable(); } /// <summary> /// Determines if any of the state sets in <see cref="GetAllHostStateSets()"/> match a specified predicate. /// </summary> /// <remarks> /// This method avoids the performance overhead of calling <see cref="GetAllHostStateSets()"/> for the /// specific case where the result is only used for testing if any element meets certain conditions. /// </remarks> public bool HasAnyHostStateSet<TArg>(Func<StateSet, TArg, bool> match, TArg arg) { foreach (var (_, hostStateSet) in _hostAnalyzerStateMap) { foreach (var stateSet in hostStateSet.OrderedStateSets) { if (match(stateSet, arg)) return true; } } return false; } /// <summary> /// Determines if any of the state sets in <see cref="_projectAnalyzerStateMap"/> for a specific project /// match a specified predicate. /// </summary> /// <remarks> /// <para>This method avoids the performance overhead of calling <see cref="GetStateSets(Project)"/> for the /// specific case where the result is only used for testing if any element meets certain conditions.</para> /// /// <para>Note that host state sets (i.e. ones retured by <see cref="GetAllHostStateSets()"/> are not tested /// by this method.</para> /// </remarks> public bool HasAnyProjectStateSet<TArg>(ProjectId projectId, Func<StateSet, TArg, bool> match, TArg arg) { if (_projectAnalyzerStateMap.TryGetValue(projectId, out var entry)) { foreach (var (_, stateSet) in entry.StateSetMap) { if (match(stateSet, arg)) return true; } } return false; } public bool OnProjectRemoved(IEnumerable<StateSet> stateSets, ProjectId projectId) { var removed = false; foreach (var stateSet in stateSets) { removed |= stateSet.OnProjectRemoved(projectId); } _projectAnalyzerStateMap.TryRemove(projectId, out _); return removed; } private void RaiseProjectAnalyzerReferenceChanged(ProjectAnalyzerReferenceChangedEventArgs args) => ProjectAnalyzerReferenceChanged?.Invoke(this, args); private static ImmutableDictionary<DiagnosticAnalyzer, StateSet> CreateStateSetMap( string language, IEnumerable<ImmutableArray<DiagnosticAnalyzer>> analyzerCollection, bool includeFileContentLoadAnalyzer) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, StateSet>(); if (includeFileContentLoadAnalyzer) { builder.Add(FileContentLoadAnalyzer.Instance, new StateSet(language, FileContentLoadAnalyzer.Instance, PredefinedBuildTools.Live)); } foreach (var analyzers in analyzerCollection) { foreach (var analyzer in analyzers) { Debug.Assert(analyzer != FileContentLoadAnalyzer.Instance); // TODO: // #1, all de-duplication should move to DiagnosticAnalyzerInfoCache // #2, not sure whether de-duplication of analyzer itself makes sense. this can only happen // if user deliberately put same analyzer twice. if (builder.ContainsKey(analyzer)) { continue; } var buildToolName = analyzer.IsBuiltInAnalyzer() ? PredefinedBuildTools.Live : analyzer.GetAnalyzerAssemblyName(); builder.Add(analyzer, new StateSet(language, analyzer, buildToolName)); } } return builder.ToImmutable(); } [Conditional("DEBUG")] private static void VerifyUniqueStateNames(IEnumerable<StateSet> stateSets) { // Ensure diagnostic state name is indeed unique. var set = new HashSet<ValueTuple<string, string>>(); foreach (var stateSet in stateSets) { Contract.ThrowIfFalse(set.Add((stateSet.Language, stateSet.StateName))); } } [Conditional("DEBUG")] private void VerifyProjectDiagnosticStates(IEnumerable<StateSet> stateSets) { // We do not de-duplicate analyzer instances across host and project analyzers. var projectAnalyzers = stateSets.Select(state => state.Analyzer).ToImmutableHashSet(); var hostStates = GetAllHostStateSets().Where(state => !projectAnalyzers.Contains(state.Analyzer)); VerifyUniqueStateNames(hostStates.Concat(stateSets)); } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/VisualBasic/Portable/BoundTree/BoundNode.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend MustInherit Class BoundNode Private ReadOnly _kind As BoundKind Private _attributes As BoundNodeAttributes Private ReadOnly _syntax As SyntaxNode <Flags()> Private Enum BoundNodeAttributes As Byte HasErrors = 1 'NOTE: the bit means "NOT OK". So that default is OK state. WasCompilerGenerated = 1 << 1 #If DEBUG Then ''' <summary> ''' Captures the fact that consumers of the node already checked the state of the WasCompilerGenerated bit. ''' Allows to assert on attempts to set WasCompilerGenerated bit after that. ''' </summary> WasCompilerGeneratedIsChecked = 1 << 2 #End If End Enum Public Sub New(kind As BoundKind, syntax As SyntaxNode) ValidateLocationInformation(kind, syntax) _kind = kind _syntax = syntax End Sub Public Sub New(kind As BoundKind, syntax As SyntaxNode, hasErrors As Boolean) MyClass.New(kind, syntax) If hasErrors Then _attributes = BoundNodeAttributes.HasErrors End If End Sub Protected Sub CopyAttributes(node As BoundNode) If node.WasCompilerGenerated Then Me.SetWasCompilerGenerated() End If End Sub <Conditional("DEBUG")> Private Shared Sub ValidateLocationInformation(kind As BoundKind, syntax As SyntaxNode) ' We should always have a syntax node and a syntax tree as well, unless it is a hidden sequence point. ' If it's a sequence point, it must have a syntax tree to retrieve the file name. Debug.Assert(kind = BoundKind.SequencePoint OrElse kind = BoundKind.SequencePointExpression OrElse syntax IsNot Nothing) End Sub Public ReadOnly Property HasErrors As Boolean Get Return (_attributes And BoundNodeAttributes.HasErrors) <> 0 End Get End Property ''' <summary> ''' The node should not be treated as a direct semantical representation of the syntax it is associated with. ''' Some examples: ''' - implicit call for base constructor is associated with the constructor syntax. ''' - code in compiler generated constructor is associated with the type declaration. ''' ''' Nodes marked this way are likely to be skipped by SemanticModel, Sequence Point rewriter, etc. ''' </summary> Public ReadOnly Property WasCompilerGenerated As Boolean Get #If DEBUG Then _attributes = _attributes Or BoundNodeAttributes.WasCompilerGeneratedIsChecked #End If Return (_attributes And BoundNodeAttributes.WasCompilerGenerated) <> 0 End Get End Property Public Sub SetWasCompilerGenerated() #If DEBUG Then Debug.Assert((_attributes And BoundNodeAttributes.WasCompilerGeneratedIsChecked) = 0) #End If _attributes = _attributes Or BoundNodeAttributes.WasCompilerGenerated End Sub Public ReadOnly Property Kind As BoundKind Get Return _kind End Get End Property Public ReadOnly Property Syntax As SyntaxNode Get Return _syntax End Get End Property Public ReadOnly Property SyntaxTree As SyntaxTree Get Return DirectCast(_syntax.SyntaxTree, VisualBasicSyntaxTree) End Get End Property Public Overridable Overloads Function Accept(visitor As BoundTreeVisitor) As BoundNode Throw ExceptionUtilities.Unreachable End Function #If DEBUG Then Private Function Dump() As String Return TreeDumper.DumpCompact(BoundTreeDumperNodeProducer.MakeTree(Me)) End Function Public Overloads Function MemberwiseClone(Of T As BoundNode)() As T Return DirectCast(Me.MemberwiseClone(), T) End Function #End If End Class ' Indicates how a particular method group or property group was qualified, so that the right ' errors/warnings can be generated after overload resolution. Friend Enum QualificationKind Unqualified ' Unqualified -- a simple name QualifiedViaValue ' Qualified through an expression that produces a variable or value QualifiedViaTypeName ' Qualified through an expression that was a type name. QualifiedViaNamespace ' Qualified through an expression that was a namespace name. End Enum End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend MustInherit Class BoundNode Private ReadOnly _kind As BoundKind Private _attributes As BoundNodeAttributes Private ReadOnly _syntax As SyntaxNode <Flags()> Private Enum BoundNodeAttributes As Byte HasErrors = 1 'NOTE: the bit means "NOT OK". So that default is OK state. WasCompilerGenerated = 1 << 1 #If DEBUG Then ''' <summary> ''' Captures the fact that consumers of the node already checked the state of the WasCompilerGenerated bit. ''' Allows to assert on attempts to set WasCompilerGenerated bit after that. ''' </summary> WasCompilerGeneratedIsChecked = 1 << 2 #End If End Enum Public Sub New(kind As BoundKind, syntax As SyntaxNode) ValidateLocationInformation(kind, syntax) _kind = kind _syntax = syntax End Sub Public Sub New(kind As BoundKind, syntax As SyntaxNode, hasErrors As Boolean) MyClass.New(kind, syntax) If hasErrors Then _attributes = BoundNodeAttributes.HasErrors End If End Sub Protected Sub CopyAttributes(node As BoundNode) If node.WasCompilerGenerated Then Me.SetWasCompilerGenerated() End If End Sub <Conditional("DEBUG")> Private Shared Sub ValidateLocationInformation(kind As BoundKind, syntax As SyntaxNode) ' We should always have a syntax node and a syntax tree as well, unless it is a hidden sequence point. ' If it's a sequence point, it must have a syntax tree to retrieve the file name. Debug.Assert(kind = BoundKind.SequencePoint OrElse kind = BoundKind.SequencePointExpression OrElse syntax IsNot Nothing) End Sub Public ReadOnly Property HasErrors As Boolean Get Return (_attributes And BoundNodeAttributes.HasErrors) <> 0 End Get End Property ''' <summary> ''' The node should not be treated as a direct semantical representation of the syntax it is associated with. ''' Some examples: ''' - implicit call for base constructor is associated with the constructor syntax. ''' - code in compiler generated constructor is associated with the type declaration. ''' ''' Nodes marked this way are likely to be skipped by SemanticModel, Sequence Point rewriter, etc. ''' </summary> Public ReadOnly Property WasCompilerGenerated As Boolean Get #If DEBUG Then _attributes = _attributes Or BoundNodeAttributes.WasCompilerGeneratedIsChecked #End If Return (_attributes And BoundNodeAttributes.WasCompilerGenerated) <> 0 End Get End Property Public Sub SetWasCompilerGenerated() #If DEBUG Then Debug.Assert((_attributes And BoundNodeAttributes.WasCompilerGeneratedIsChecked) = 0) #End If _attributes = _attributes Or BoundNodeAttributes.WasCompilerGenerated End Sub Public ReadOnly Property Kind As BoundKind Get Return _kind End Get End Property Public ReadOnly Property Syntax As SyntaxNode Get Return _syntax End Get End Property Public ReadOnly Property SyntaxTree As SyntaxTree Get Return DirectCast(_syntax.SyntaxTree, VisualBasicSyntaxTree) End Get End Property Public Overridable Overloads Function Accept(visitor As BoundTreeVisitor) As BoundNode Throw ExceptionUtilities.Unreachable End Function #If DEBUG Then Private Function Dump() As String Return TreeDumper.DumpCompact(BoundTreeDumperNodeProducer.MakeTree(Me)) End Function Public Overloads Function MemberwiseClone(Of T As BoundNode)() As T Return DirectCast(Me.MemberwiseClone(), T) End Function #End If End Class ' Indicates how a particular method group or property group was qualified, so that the right ' errors/warnings can be generated after overload resolution. Friend Enum QualificationKind Unqualified ' Unqualified -- a simple name QualifiedViaValue ' Qualified through an expression that produces a variable or value QualifiedViaTypeName ' Qualified through an expression that was a type name. QualifiedViaNamespace ' Qualified through an expression that was a namespace name. End Enum End Namespace
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/VisualStudio/Core/Def/Implementation/ChangeSignature/ChangeSignatureDialog.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { /// <summary> /// Interaction logic for ChangeSignatureDialog.xaml /// </summary> internal partial class ChangeSignatureDialog : DialogWindow { private readonly ChangeSignatureDialogViewModel _viewModel; // Expose localized strings for binding public static string ChangeSignatureDialogTitle { get { return ServicesVSResources.Change_Signature; } } public static string CurrentParameter { get { return ServicesVSResources.Current_parameter; } } public static string Parameters { get { return ServicesVSResources.Parameters_colon2; } } public static string PreviewMethodSignature { get { return ServicesVSResources.Preview_method_signature_colon; } } public static string PreviewReferenceChanges { get { return ServicesVSResources.Preview_reference_changes; } } public static string Remove { get { return ServicesVSResources.Re_move; } } public static string Restore { get { return ServicesVSResources.Restore; } } public static string Add { get { return ServicesVSResources.Add; } } public static string OK { get { return ServicesVSResources.OK; } } public static string Cancel { get { return ServicesVSResources.Cancel; } } public static string WarningTypeDoesNotBind { get { return ServicesVSResources.Warning_colon_type_does_not_bind; } } public static string WarningDuplicateParameterName { get { return ServicesVSResources.Warning_colon_duplicate_parameter_name; } } public Brush ParameterText { get; } public Brush RemovedParameterText { get; } public Brush DisabledParameterForeground { get; } public Brush DisabledParameterBackground { get; } public Brush StrikethroughBrush { get; } // Use C# Reorder Parameters helpTopic for C# and VB. internal ChangeSignatureDialog(ChangeSignatureDialogViewModel viewModel) : base(helpTopic: "vs.csharp.refactoring.reorder") { _viewModel = viewModel; InitializeComponent(); // Set these headers explicitly because binding to DataGridTextColumn.Header is not // supported. modifierHeader.Header = ServicesVSResources.Modifier; defaultHeader.Header = ServicesVSResources.Default_; typeHeader.Header = ServicesVSResources.Type; parameterHeader.Header = ServicesVSResources.Parameter; callsiteHeader.Header = ServicesVSResources.Callsite; indexHeader.Header = ServicesVSResources.Index; ParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0x1E, 0x1E, 0x1E)); RemovedParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Gray); DisabledParameterBackground = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xDF, 0xE7, 0xF3)); DisabledParameterForeground = SystemParameters.HighContrast ? SystemColors.GrayTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xA2, 0xA4, 0xA5)); Members.Background = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF)); StrikethroughBrush = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Red); DataContext = viewModel; Loaded += ChangeSignatureDialog_Loaded; } private void ChangeSignatureDialog_Loaded(object sender, RoutedEventArgs e) => Members.Focus(); private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; private void MoveUp_Click(object sender, EventArgs e) { MoveUp_UpdateSelectedIndex(); SetFocusToSelectedRow(false); } private void MoveUp_Click_FocusRow(object sender, EventArgs e) { MoveUp_UpdateSelectedIndex(); SetFocusToSelectedRow(true); } private void MoveUp_UpdateSelectedIndex() { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveUp && oldSelectedIndex >= 0) { _viewModel.MoveUp(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex - 1; } } private void MoveDown_Click(object sender, EventArgs e) { MoveDown_UpdateSelectedIndex(); SetFocusToSelectedRow(false); } private void MoveDown_Click_FocusRow(object sender, EventArgs e) { MoveDown_UpdateSelectedIndex(); SetFocusToSelectedRow(true); } private void MoveDown_UpdateSelectedIndex() { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveDown && oldSelectedIndex >= 0) { _viewModel.MoveDown(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex + 1; } } private void Remove_Click(object sender, RoutedEventArgs e) { if (_viewModel.CanRemove) { _viewModel.Remove(); Members.Items.Refresh(); } SetFocusToSelectedRow(true); } private void Restore_Click(object sender, RoutedEventArgs e) { if (_viewModel.CanRestore) { _viewModel.Restore(); Members.Items.Refresh(); } SetFocusToSelectedRow(true); } private void Add_Click(object sender, RoutedEventArgs e) { var addParameterViewModel = _viewModel.CreateAddParameterDialogViewModel(); var dialog = new AddParameterDialog(addParameterViewModel); var result = dialog.ShowModal(); ChangeSignatureLogger.LogAddParameterDialogLaunched(); if (result.HasValue && result.Value) { ChangeSignatureLogger.LogAddParameterDialogCommitted(); var addedParameter = new AddedParameter( addParameterViewModel.TypeSymbol, addParameterViewModel.TypeName, addParameterViewModel.ParameterName, GetCallSiteKind(addParameterViewModel), addParameterViewModel.IsCallsiteRegularValue ? addParameterViewModel.CallSiteValue : string.Empty, addParameterViewModel.IsRequired, addParameterViewModel.IsRequired ? string.Empty : addParameterViewModel.DefaultValue, addParameterViewModel.TypeBinds); _viewModel.AddParameter(addedParameter); } SetFocusToSelectedRow(false); } private static CallSiteKind GetCallSiteKind(AddParameterDialogViewModel addParameterViewModel) { if (addParameterViewModel.IsCallsiteInferred) return CallSiteKind.Inferred; if (addParameterViewModel.IsCallsiteOmitted) return CallSiteKind.Omitted; if (addParameterViewModel.IsCallsiteTodo) return CallSiteKind.Todo; Debug.Assert(addParameterViewModel.IsCallsiteRegularValue); return addParameterViewModel.UseNamedArguments ? CallSiteKind.ValueWithName : CallSiteKind.Value; } private void SetFocusToSelectedRow(bool focusRow) { if (Members.SelectedIndex >= 0) { if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not DataGridRow row) { Members.ScrollIntoView(Members.SelectedItem); row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as DataGridRow; } if (row != null && focusRow) { // This line is required primarily for accessibility purposes to ensure the screenreader always // focuses on individual rows rather than the parent DataGrid. Members.UpdateLayout(); FocusRow(row); } } } private static void FocusRow(DataGridRow row) { var cell = row.FindDescendant<DataGridCell>(); if (cell != null) { cell.Focus(); } } private void MoveSelectionUp_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (oldSelectedIndex > 0) { var potentialNewSelectedParameter = Members.Items[oldSelectedIndex - 1] as ChangeSignatureDialogViewModel.ParameterViewModel; if (!potentialNewSelectedParameter.IsDisabled) { Members.SelectedIndex = oldSelectedIndex - 1; } } SetFocusToSelectedRow(true); } private void MoveSelectionDown_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (oldSelectedIndex >= 0 && oldSelectedIndex < Members.Items.Count - 1) { Members.SelectedIndex = oldSelectedIndex + 1; } SetFocusToSelectedRow(true); } private void Members_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { if (Members.CurrentItem != null) { // When it has a valid value, CurrentItem is generally more up-to-date than SelectedIndex. // For example, if the user clicks on an out of view item in the parameter list (i.e. the // parameter list is long and the user scrolls to click another parameter farther down/up // in the list), CurrentItem will update immediately while SelectedIndex will not. Members.SelectedIndex = Members.Items.IndexOf(Members.CurrentItem); } if (Members.SelectedIndex == -1) { Members.SelectedIndex = _viewModel.GetStartingSelectionIndex(); } SetFocusToSelectedRow(true); } private void ToggleRemovedState(object sender, ExecutedRoutedEventArgs e) { if (_viewModel.CanRemove) { _viewModel.Remove(); } else if (_viewModel.CanRestore) { _viewModel.Restore(); } Members.Items.Refresh(); SetFocusToSelectedRow(true); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly ChangeSignatureDialog _dialog; public TestAccessor(ChangeSignatureDialog dialog) => _dialog = dialog; public ChangeSignatureDialogViewModel ViewModel => _dialog._viewModel; public DataGrid Members => _dialog.Members; public DialogButton OKButton => _dialog.OKButton; public DialogButton CancelButton => _dialog.CancelButton; public DialogButton DownButton => _dialog.DownButton; public DialogButton UpButton => _dialog.UpButton; public DialogButton AddButton => _dialog.AddButton; public DialogButton RemoveButton => _dialog.RemoveButton; public DialogButton RestoreButton => _dialog.RestoreButton; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis.ChangeSignature; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature { /// <summary> /// Interaction logic for ChangeSignatureDialog.xaml /// </summary> internal partial class ChangeSignatureDialog : DialogWindow { private readonly ChangeSignatureDialogViewModel _viewModel; // Expose localized strings for binding public static string ChangeSignatureDialogTitle { get { return ServicesVSResources.Change_Signature; } } public static string CurrentParameter { get { return ServicesVSResources.Current_parameter; } } public static string Parameters { get { return ServicesVSResources.Parameters_colon2; } } public static string PreviewMethodSignature { get { return ServicesVSResources.Preview_method_signature_colon; } } public static string PreviewReferenceChanges { get { return ServicesVSResources.Preview_reference_changes; } } public static string Remove { get { return ServicesVSResources.Re_move; } } public static string Restore { get { return ServicesVSResources.Restore; } } public static string Add { get { return ServicesVSResources.Add; } } public static string OK { get { return ServicesVSResources.OK; } } public static string Cancel { get { return ServicesVSResources.Cancel; } } public static string WarningTypeDoesNotBind { get { return ServicesVSResources.Warning_colon_type_does_not_bind; } } public static string WarningDuplicateParameterName { get { return ServicesVSResources.Warning_colon_duplicate_parameter_name; } } public Brush ParameterText { get; } public Brush RemovedParameterText { get; } public Brush DisabledParameterForeground { get; } public Brush DisabledParameterBackground { get; } public Brush StrikethroughBrush { get; } // Use C# Reorder Parameters helpTopic for C# and VB. internal ChangeSignatureDialog(ChangeSignatureDialogViewModel viewModel) : base(helpTopic: "vs.csharp.refactoring.reorder") { _viewModel = viewModel; InitializeComponent(); // Set these headers explicitly because binding to DataGridTextColumn.Header is not // supported. modifierHeader.Header = ServicesVSResources.Modifier; defaultHeader.Header = ServicesVSResources.Default_; typeHeader.Header = ServicesVSResources.Type; parameterHeader.Header = ServicesVSResources.Parameter; callsiteHeader.Header = ServicesVSResources.Callsite; indexHeader.Header = ServicesVSResources.Index; ParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0x1E, 0x1E, 0x1E)); RemovedParameterText = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Gray); DisabledParameterBackground = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xDF, 0xE7, 0xF3)); DisabledParameterForeground = SystemParameters.HighContrast ? SystemColors.GrayTextBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xA2, 0xA4, 0xA5)); Members.Background = SystemParameters.HighContrast ? SystemColors.WindowBrush : new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF)); StrikethroughBrush = SystemParameters.HighContrast ? SystemColors.WindowTextBrush : new SolidColorBrush(Colors.Red); DataContext = viewModel; Loaded += ChangeSignatureDialog_Loaded; } private void ChangeSignatureDialog_Loaded(object sender, RoutedEventArgs e) => Members.Focus(); private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; private void MoveUp_Click(object sender, EventArgs e) { MoveUp_UpdateSelectedIndex(); SetFocusToSelectedRow(false); } private void MoveUp_Click_FocusRow(object sender, EventArgs e) { MoveUp_UpdateSelectedIndex(); SetFocusToSelectedRow(true); } private void MoveUp_UpdateSelectedIndex() { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveUp && oldSelectedIndex >= 0) { _viewModel.MoveUp(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex - 1; } } private void MoveDown_Click(object sender, EventArgs e) { MoveDown_UpdateSelectedIndex(); SetFocusToSelectedRow(false); } private void MoveDown_Click_FocusRow(object sender, EventArgs e) { MoveDown_UpdateSelectedIndex(); SetFocusToSelectedRow(true); } private void MoveDown_UpdateSelectedIndex() { var oldSelectedIndex = Members.SelectedIndex; if (_viewModel.CanMoveDown && oldSelectedIndex >= 0) { _viewModel.MoveDown(); Members.Items.Refresh(); Members.SelectedIndex = oldSelectedIndex + 1; } } private void Remove_Click(object sender, RoutedEventArgs e) { if (_viewModel.CanRemove) { _viewModel.Remove(); Members.Items.Refresh(); } SetFocusToSelectedRow(true); } private void Restore_Click(object sender, RoutedEventArgs e) { if (_viewModel.CanRestore) { _viewModel.Restore(); Members.Items.Refresh(); } SetFocusToSelectedRow(true); } private void Add_Click(object sender, RoutedEventArgs e) { var addParameterViewModel = _viewModel.CreateAddParameterDialogViewModel(); var dialog = new AddParameterDialog(addParameterViewModel); var result = dialog.ShowModal(); ChangeSignatureLogger.LogAddParameterDialogLaunched(); if (result.HasValue && result.Value) { ChangeSignatureLogger.LogAddParameterDialogCommitted(); var addedParameter = new AddedParameter( addParameterViewModel.TypeSymbol, addParameterViewModel.TypeName, addParameterViewModel.ParameterName, GetCallSiteKind(addParameterViewModel), addParameterViewModel.IsCallsiteRegularValue ? addParameterViewModel.CallSiteValue : string.Empty, addParameterViewModel.IsRequired, addParameterViewModel.IsRequired ? string.Empty : addParameterViewModel.DefaultValue, addParameterViewModel.TypeBinds); _viewModel.AddParameter(addedParameter); } SetFocusToSelectedRow(false); } private static CallSiteKind GetCallSiteKind(AddParameterDialogViewModel addParameterViewModel) { if (addParameterViewModel.IsCallsiteInferred) return CallSiteKind.Inferred; if (addParameterViewModel.IsCallsiteOmitted) return CallSiteKind.Omitted; if (addParameterViewModel.IsCallsiteTodo) return CallSiteKind.Todo; Debug.Assert(addParameterViewModel.IsCallsiteRegularValue); return addParameterViewModel.UseNamedArguments ? CallSiteKind.ValueWithName : CallSiteKind.Value; } private void SetFocusToSelectedRow(bool focusRow) { if (Members.SelectedIndex >= 0) { if (Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is not DataGridRow row) { Members.ScrollIntoView(Members.SelectedItem); row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as DataGridRow; } if (row != null && focusRow) { // This line is required primarily for accessibility purposes to ensure the screenreader always // focuses on individual rows rather than the parent DataGrid. Members.UpdateLayout(); FocusRow(row); } } } private static void FocusRow(DataGridRow row) { var cell = row.FindDescendant<DataGridCell>(); if (cell != null) { cell.Focus(); } } private void MoveSelectionUp_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (oldSelectedIndex > 0) { var potentialNewSelectedParameter = Members.Items[oldSelectedIndex - 1] as ChangeSignatureDialogViewModel.ParameterViewModel; if (!potentialNewSelectedParameter.IsDisabled) { Members.SelectedIndex = oldSelectedIndex - 1; } } SetFocusToSelectedRow(true); } private void MoveSelectionDown_Click(object sender, EventArgs e) { var oldSelectedIndex = Members.SelectedIndex; if (oldSelectedIndex >= 0 && oldSelectedIndex < Members.Items.Count - 1) { Members.SelectedIndex = oldSelectedIndex + 1; } SetFocusToSelectedRow(true); } private void Members_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { if (Members.CurrentItem != null) { // When it has a valid value, CurrentItem is generally more up-to-date than SelectedIndex. // For example, if the user clicks on an out of view item in the parameter list (i.e. the // parameter list is long and the user scrolls to click another parameter farther down/up // in the list), CurrentItem will update immediately while SelectedIndex will not. Members.SelectedIndex = Members.Items.IndexOf(Members.CurrentItem); } if (Members.SelectedIndex == -1) { Members.SelectedIndex = _viewModel.GetStartingSelectionIndex(); } SetFocusToSelectedRow(true); } private void ToggleRemovedState(object sender, ExecutedRoutedEventArgs e) { if (_viewModel.CanRemove) { _viewModel.Remove(); } else if (_viewModel.CanRestore) { _viewModel.Restore(); } Members.Items.Refresh(); SetFocusToSelectedRow(true); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly ChangeSignatureDialog _dialog; public TestAccessor(ChangeSignatureDialog dialog) => _dialog = dialog; public ChangeSignatureDialogViewModel ViewModel => _dialog._viewModel; public DataGrid Members => _dialog.Members; public DialogButton OKButton => _dialog.OKButton; public DialogButton CancelButton => _dialog.CancelButton; public DialogButton DownButton => _dialog.DownButton; public DialogButton UpButton => _dialog.UpButton; public DialogButton AddButton => _dialog.AddButton; public DialogButton RemoveButton => _dialog.RemoveButton; public DialogButton RestoreButton => _dialog.RestoreButton; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_StackAlloc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression stackAllocNode) { return VisitStackAllocArrayCreationBase(stackAllocNode); } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation stackAllocNode) { return VisitStackAllocArrayCreationBase(stackAllocNode); } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase stackAllocNode) { var rewrittenCount = VisitExpression(stackAllocNode.Count); var type = stackAllocNode.Type; Debug.Assert(type is { }); if (rewrittenCount.ConstantValue?.Int32Value == 0) { // either default(span) or nullptr return _factory.Default(type); } var elementType = stackAllocNode.ElementType; var initializerOpt = stackAllocNode.InitializerOpt; if (initializerOpt != null) { initializerOpt = initializerOpt.Update(VisitList(initializerOpt.Initializers)); } if (type.IsPointerType()) { var stackSize = RewriteStackAllocCountToSize(rewrittenCount, elementType); return new BoundConvertedStackAllocExpression(stackAllocNode.Syntax, elementType, stackSize, initializerOpt, type); } else if (TypeSymbol.Equals(type.OriginalDefinition, _compilation.GetWellKnownType(WellKnownType.System_Span_T), TypeCompareKind.ConsiderEverything2)) { var spanType = (NamedTypeSymbol)type; var sideEffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); var countTemp = CaptureExpressionInTempIfNeeded(rewrittenCount, sideEffects, locals, SynthesizedLocalKind.Spill); var stackSize = RewriteStackAllocCountToSize(countTemp, elementType); stackAllocNode = new BoundConvertedStackAllocExpression( stackAllocNode.Syntax, elementType, stackSize, initializerOpt, _compilation.CreatePointerTypeSymbol(elementType)); BoundExpression constructorCall; if (TryGetWellKnownTypeMember(stackAllocNode.Syntax, WellKnownMember.System_Span_T__ctor, out MethodSymbol spanConstructor)) { constructorCall = _factory.New((MethodSymbol)spanConstructor.SymbolAsMember(spanType), stackAllocNode, countTemp); } else { constructorCall = new BoundBadExpression( syntax: stackAllocNode.Syntax, resultKind: LookupResultKind.NotInvocable, symbols: ImmutableArray<Symbol?>.Empty, childBoundNodes: ImmutableArray<BoundExpression>.Empty, type: ErrorTypeSymbol.UnknownResultType); } // The stackalloc instruction requires that the evaluation stack contains only its parameter when executed. // We arrange to clear the stack by wrapping it in a SpillSequence, which will cause pending computations // to be spilled, and also by storing the result in a temporary local, so that the result does not get // hoisted/spilled into some state machine. If that temp local needs to be spilled that will result in an // error. _needsSpilling = true; var tempAccess = _factory.StoreToTemp(constructorCall, out BoundAssignmentOperator tempAssignment, syntaxOpt: stackAllocNode.Syntax); sideEffects.Add(tempAssignment); locals.Add(tempAccess.LocalSymbol); return new BoundSpillSequence( syntax: stackAllocNode.Syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideEffects.ToImmutableAndFree(), value: tempAccess, type: spanType); } else { throw ExceptionUtilities.UnexpectedValue(type); } } private BoundExpression RewriteStackAllocCountToSize(BoundExpression countExpression, TypeSymbol elementType) { // From ILGENREC::genExpr: // EDMAURER always perform a checked multiply regardless of the context. // localloc takes an unsigned native int. When a user specifies a negative // count of elements, per spec, the behavior is undefined. So convert element // count to unsigned. // NOTE: to match this special case logic, we're going to construct the multiplication // ourselves, rather than calling MakeSizeOfMultiplication (which inserts various checks // and conversions). TypeSymbol uintType = _factory.SpecialType(SpecialType.System_UInt32); TypeSymbol uintPtrType = _factory.SpecialType(SpecialType.System_UIntPtr); // Why convert twice? Because dev10 actually uses an explicit conv_u instruction and the normal conversion // from int32 to native uint is emitted as conv_i. The behavior we want to emulate is to re-interpret // (i.e. unchecked) an int32 as unsigned (i.e. uint32) and then convert it to a native uint *without* sign // extension. BoundExpression sizeOfExpression = _factory.Sizeof(elementType); var sizeConst = sizeOfExpression.ConstantValue; if (sizeConst != null) { int size = sizeConst.Int32Value; Debug.Assert(size > 0); // common case: stackalloc int[123] var countConst = countExpression.ConstantValue; if (countConst != null) { var count = countConst.Int32Value; long folded = unchecked((uint)count * size); if (folded < uint.MaxValue) { return _factory.Convert(uintPtrType, _factory.Literal((uint)folded), Conversion.IntegerToPointer); } } } BoundExpression convertedCount = _factory.Convert(uintType, countExpression, Conversion.ExplicitNumeric); convertedCount = _factory.Convert(uintPtrType, convertedCount, Conversion.IntegerToPointer); // another common case: stackalloc byte[x] if (sizeConst?.Int32Value == 1) { return convertedCount; } BinaryOperatorKind multiplicationKind = BinaryOperatorKind.Checked | BinaryOperatorKind.UIntMultiplication; //"UInt" just to make it unsigned BoundExpression product = _factory.Binary(multiplicationKind, uintPtrType, convertedCount, sizeOfExpression); return product; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression stackAllocNode) { return VisitStackAllocArrayCreationBase(stackAllocNode); } public override BoundNode VisitStackAllocArrayCreation(BoundStackAllocArrayCreation stackAllocNode) { return VisitStackAllocArrayCreationBase(stackAllocNode); } private BoundNode VisitStackAllocArrayCreationBase(BoundStackAllocArrayCreationBase stackAllocNode) { var rewrittenCount = VisitExpression(stackAllocNode.Count); var type = stackAllocNode.Type; Debug.Assert(type is { }); if (rewrittenCount.ConstantValue?.Int32Value == 0) { // either default(span) or nullptr return _factory.Default(type); } var elementType = stackAllocNode.ElementType; var initializerOpt = stackAllocNode.InitializerOpt; if (initializerOpt != null) { initializerOpt = initializerOpt.Update(VisitList(initializerOpt.Initializers)); } if (type.IsPointerType()) { var stackSize = RewriteStackAllocCountToSize(rewrittenCount, elementType); return new BoundConvertedStackAllocExpression(stackAllocNode.Syntax, elementType, stackSize, initializerOpt, type); } else if (TypeSymbol.Equals(type.OriginalDefinition, _compilation.GetWellKnownType(WellKnownType.System_Span_T), TypeCompareKind.ConsiderEverything2)) { var spanType = (NamedTypeSymbol)type; var sideEffects = ArrayBuilder<BoundExpression>.GetInstance(); var locals = ArrayBuilder<LocalSymbol>.GetInstance(); var countTemp = CaptureExpressionInTempIfNeeded(rewrittenCount, sideEffects, locals, SynthesizedLocalKind.Spill); var stackSize = RewriteStackAllocCountToSize(countTemp, elementType); stackAllocNode = new BoundConvertedStackAllocExpression( stackAllocNode.Syntax, elementType, stackSize, initializerOpt, _compilation.CreatePointerTypeSymbol(elementType)); BoundExpression constructorCall; if (TryGetWellKnownTypeMember(stackAllocNode.Syntax, WellKnownMember.System_Span_T__ctor, out MethodSymbol spanConstructor)) { constructorCall = _factory.New((MethodSymbol)spanConstructor.SymbolAsMember(spanType), stackAllocNode, countTemp); } else { constructorCall = new BoundBadExpression( syntax: stackAllocNode.Syntax, resultKind: LookupResultKind.NotInvocable, symbols: ImmutableArray<Symbol?>.Empty, childBoundNodes: ImmutableArray<BoundExpression>.Empty, type: ErrorTypeSymbol.UnknownResultType); } // The stackalloc instruction requires that the evaluation stack contains only its parameter when executed. // We arrange to clear the stack by wrapping it in a SpillSequence, which will cause pending computations // to be spilled, and also by storing the result in a temporary local, so that the result does not get // hoisted/spilled into some state machine. If that temp local needs to be spilled that will result in an // error. _needsSpilling = true; var tempAccess = _factory.StoreToTemp(constructorCall, out BoundAssignmentOperator tempAssignment, syntaxOpt: stackAllocNode.Syntax); sideEffects.Add(tempAssignment); locals.Add(tempAccess.LocalSymbol); return new BoundSpillSequence( syntax: stackAllocNode.Syntax, locals: locals.ToImmutableAndFree(), sideEffects: sideEffects.ToImmutableAndFree(), value: tempAccess, type: spanType); } else { throw ExceptionUtilities.UnexpectedValue(type); } } private BoundExpression RewriteStackAllocCountToSize(BoundExpression countExpression, TypeSymbol elementType) { // From ILGENREC::genExpr: // EDMAURER always perform a checked multiply regardless of the context. // localloc takes an unsigned native int. When a user specifies a negative // count of elements, per spec, the behavior is undefined. So convert element // count to unsigned. // NOTE: to match this special case logic, we're going to construct the multiplication // ourselves, rather than calling MakeSizeOfMultiplication (which inserts various checks // and conversions). TypeSymbol uintType = _factory.SpecialType(SpecialType.System_UInt32); TypeSymbol uintPtrType = _factory.SpecialType(SpecialType.System_UIntPtr); // Why convert twice? Because dev10 actually uses an explicit conv_u instruction and the normal conversion // from int32 to native uint is emitted as conv_i. The behavior we want to emulate is to re-interpret // (i.e. unchecked) an int32 as unsigned (i.e. uint32) and then convert it to a native uint *without* sign // extension. BoundExpression sizeOfExpression = _factory.Sizeof(elementType); var sizeConst = sizeOfExpression.ConstantValue; if (sizeConst != null) { int size = sizeConst.Int32Value; Debug.Assert(size > 0); // common case: stackalloc int[123] var countConst = countExpression.ConstantValue; if (countConst != null) { var count = countConst.Int32Value; long folded = unchecked((uint)count * size); if (folded < uint.MaxValue) { return _factory.Convert(uintPtrType, _factory.Literal((uint)folded), Conversion.IntegerToPointer); } } } BoundExpression convertedCount = _factory.Convert(uintType, countExpression, Conversion.ExplicitNumeric); convertedCount = _factory.Convert(uintPtrType, convertedCount, Conversion.IntegerToPointer); // another common case: stackalloc byte[x] if (sizeConst?.Int32Value == 1) { return convertedCount; } BinaryOperatorKind multiplicationKind = BinaryOperatorKind.Checked | BinaryOperatorKind.UIntMultiplication; //"UInt" just to make it unsigned BoundExpression product = _factory.Binary(multiplicationKind, uintPtrType, convertedCount, sizeOfExpression); return product; } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Analyzers/Core/Analyzers/AbstractBuiltInCodeStyleDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CodeStyle { internal abstract partial class AbstractBuiltInCodeStyleDiagnosticAnalyzer { /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// unique <see cref="IPerLanguageOption"/> code style option. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="option"> /// Per-language option that can be used to configure the given <paramref name="diagnosticId"/>. /// <see langword="null"/>, if there is no such unique option. /// </param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// <see langword="null"/> if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, IPerLanguageOption? option, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { AddDiagnosticIdToOptionMapping(diagnosticId, option); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// unique <see cref="ILanguageSpecificOption"/> code style option for the given language. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="option"> /// Language specific option that can be used to configure the given <paramref name="diagnosticId"/>. /// <see langword="null"/>, if there is no such unique option. /// </param> /// <param name="language">Language for the given language-specific <paramref name="option"/>.</param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// <see langword="null"/> if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ILanguageSpecificOption? option, string language, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { AddDiagnosticIdToOptionMapping(diagnosticId, option, language); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// two or more <see cref="IPerLanguageOption"/> code style options. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="options"> /// Set of two or more per-language options that can be used to configure the diagnostic severity of the given diagnosticId. /// </param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// Null if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ImmutableHashSet<IPerLanguageOption> options, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { RoslynDebug.Assert(options != null); Debug.Assert(options.Count > 1); AddDiagnosticIdToOptionMapping(diagnosticId, options); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// two or more <see cref="ILanguageSpecificOption"/> code style options for the given language. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="options"> /// Set of two or more language-specific options that can be used to configure the diagnostic severity of the given diagnosticId. /// </param> /// <param name="language">Language for the given language-specific <paramref name="options"/>.</param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// Null if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ImmutableHashSet<ILanguageSpecificOption> options, string language, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { RoslynDebug.Assert(options != null); Debug.Assert(options.Count > 1); AddDiagnosticIdToOptionMapping(diagnosticId, options, language); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with per-language options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer(ImmutableDictionary<DiagnosticDescriptor, IPerLanguageOption> supportedDiagnosticsWithOptions) : this(supportedDiagnosticsWithOptions.Keys.ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with language-specific options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> supportedDiagnosticsWithOptions, string language) : this(supportedDiagnosticsWithOptions.Keys.ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option, language); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with a mix of language-specific and per-language options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> supportedDiagnosticsWithLangaugeSpecificOptions, ImmutableDictionary<DiagnosticDescriptor, IPerLanguageOption> supportedDiagnosticsWithPerLanguageOptions, string language) : this(supportedDiagnosticsWithLangaugeSpecificOptions.Keys.Concat(supportedDiagnosticsWithPerLanguageOptions.Keys).ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithLangaugeSpecificOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option, language); foreach (var (descriptor, option) in supportedDiagnosticsWithPerLanguageOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option); } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, IPerLanguageOption? option) { if (option != null) { AddDiagnosticIdToOptionMapping(diagnosticId, ImmutableHashSet.Create(option)); } } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ILanguageSpecificOption? option, string language) { if (option != null) { AddDiagnosticIdToOptionMapping(diagnosticId, ImmutableHashSet.Create(option), language); } } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> options) => IDEDiagnosticIdToOptionMappingHelper.AddOptionMapping(diagnosticId, options); private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> options, string language) => IDEDiagnosticIdToOptionMappingHelper.AddOptionMapping(diagnosticId, options, language); public abstract DiagnosticAnalyzerCategory GetAnalyzerCategory(); public virtual bool OpenFileOnly(OptionSet options) => 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; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CodeStyle { internal abstract partial class AbstractBuiltInCodeStyleDiagnosticAnalyzer { /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// unique <see cref="IPerLanguageOption"/> code style option. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="option"> /// Per-language option that can be used to configure the given <paramref name="diagnosticId"/>. /// <see langword="null"/>, if there is no such unique option. /// </param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// <see langword="null"/> if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, IPerLanguageOption? option, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { AddDiagnosticIdToOptionMapping(diagnosticId, option); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// unique <see cref="ILanguageSpecificOption"/> code style option for the given language. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="option"> /// Language specific option that can be used to configure the given <paramref name="diagnosticId"/>. /// <see langword="null"/>, if there is no such unique option. /// </param> /// <param name="language">Language for the given language-specific <paramref name="option"/>.</param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// <see langword="null"/> if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ILanguageSpecificOption? option, string language, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { AddDiagnosticIdToOptionMapping(diagnosticId, option, language); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// two or more <see cref="IPerLanguageOption"/> code style options. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="options"> /// Set of two or more per-language options that can be used to configure the diagnostic severity of the given diagnosticId. /// </param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// Null if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ImmutableHashSet<IPerLanguageOption> options, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { RoslynDebug.Assert(options != null); Debug.Assert(options.Count > 1); AddDiagnosticIdToOptionMapping(diagnosticId, options); } /// <summary> /// Constructor for a code style analyzer with a single diagnostic descriptor and /// two or more <see cref="ILanguageSpecificOption"/> code style options for the given language. /// </summary> /// <param name="diagnosticId">Diagnostic ID reported by this analyzer</param> /// <param name="enforceOnBuild">Build enforcement recommendation for this analyzer</param> /// <param name="options"> /// Set of two or more language-specific options that can be used to configure the diagnostic severity of the given diagnosticId. /// </param> /// <param name="language">Language for the given language-specific <paramref name="options"/>.</param> /// <param name="title">Title for the diagnostic descriptor</param> /// <param name="messageFormat"> /// Message for the diagnostic descriptor. /// Null if the message is identical to the title. /// </param> /// <param name="isUnnecessary"><see langword="true"/> if the diagnostic is reported on unnecessary code; otherwise, <see langword="false"/>.</param> /// <param name="configurable">Flag indicating if the reported diagnostics are configurable by the end users</param> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( string diagnosticId, EnforceOnBuild enforceOnBuild, ImmutableHashSet<ILanguageSpecificOption> options, string language, LocalizableString title, LocalizableString? messageFormat = null, bool isUnnecessary = false, bool configurable = true) : this(diagnosticId, enforceOnBuild, title, messageFormat, isUnnecessary, configurable) { RoslynDebug.Assert(options != null); Debug.Assert(options.Count > 1); AddDiagnosticIdToOptionMapping(diagnosticId, options, language); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with per-language options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer(ImmutableDictionary<DiagnosticDescriptor, IPerLanguageOption> supportedDiagnosticsWithOptions) : this(supportedDiagnosticsWithOptions.Keys.ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with language-specific options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> supportedDiagnosticsWithOptions, string language) : this(supportedDiagnosticsWithOptions.Keys.ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option, language); } /// <summary> /// Constructor for a code style analyzer with a multiple diagnostic descriptors with a mix of language-specific and per-language options that can be used to configure each descriptor. /// </summary> protected AbstractBuiltInCodeStyleDiagnosticAnalyzer( ImmutableDictionary<DiagnosticDescriptor, ILanguageSpecificOption> supportedDiagnosticsWithLangaugeSpecificOptions, ImmutableDictionary<DiagnosticDescriptor, IPerLanguageOption> supportedDiagnosticsWithPerLanguageOptions, string language) : this(supportedDiagnosticsWithLangaugeSpecificOptions.Keys.Concat(supportedDiagnosticsWithPerLanguageOptions.Keys).ToImmutableArray()) { foreach (var (descriptor, option) in supportedDiagnosticsWithLangaugeSpecificOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option, language); foreach (var (descriptor, option) in supportedDiagnosticsWithPerLanguageOptions) AddDiagnosticIdToOptionMapping(descriptor.Id, option); } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, IPerLanguageOption? option) { if (option != null) { AddDiagnosticIdToOptionMapping(diagnosticId, ImmutableHashSet.Create(option)); } } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ILanguageSpecificOption? option, string language) { if (option != null) { AddDiagnosticIdToOptionMapping(diagnosticId, ImmutableHashSet.Create(option), language); } } private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ImmutableHashSet<IPerLanguageOption> options) => IDEDiagnosticIdToOptionMappingHelper.AddOptionMapping(diagnosticId, options); private static void AddDiagnosticIdToOptionMapping(string diagnosticId, ImmutableHashSet<ILanguageSpecificOption> options, string language) => IDEDiagnosticIdToOptionMappingHelper.AddOptionMapping(diagnosticId, options, language); public abstract DiagnosticAnalyzerCategory GetAnalyzerCategory(); public virtual bool OpenFileOnly(OptionSet options) => false; } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/Portable/InternalUtilities/ConcurrentSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; namespace Roslyn.Utilities { /// <summary> /// A concurrent, simplified HashSet. /// </summary> [DebuggerDisplay("Count = {Count}")] internal sealed class ConcurrentSet<T> : ICollection<T> where T : notnull { /// <summary> /// The default concurrency level is 2. That means the collection can cope with up to two /// threads making simultaneous modifications without blocking. /// Note ConcurrentDictionary's default concurrency level is dynamic, scaling according to /// the number of processors. /// </summary> private const int DefaultConcurrencyLevel = 2; /// <summary> /// Taken from ConcurrentDictionary.DEFAULT_CAPACITY /// </summary> private const int DefaultCapacity = 31; /// <summary> /// The backing dictionary. The values are never used; just the keys. /// </summary> private readonly ConcurrentDictionary<T, byte> _dictionary; /// <summary> /// Construct a concurrent set with the default concurrency level. /// </summary> public ConcurrentSet() { _dictionary = new ConcurrentDictionary<T, byte>(DefaultConcurrencyLevel, DefaultCapacity); } /// <summary> /// Construct a concurrent set using the specified equality comparer. /// </summary> /// <param name="equalityComparer">The equality comparer for values in the set.</param> public ConcurrentSet(IEqualityComparer<T> equalityComparer) { _dictionary = new ConcurrentDictionary<T, byte>(DefaultConcurrencyLevel, DefaultCapacity, equalityComparer); } /// <summary> /// Obtain the number of elements in the set. /// </summary> /// <returns>The number of elements in the set.</returns> public int Count => _dictionary.Count; /// <summary> /// Determine whether the set is empty.</summary> /// <returns>true if the set is empty; otherwise, false.</returns> public bool IsEmpty => _dictionary.IsEmpty; public bool IsReadOnly => false; /// <summary> /// Determine whether the given value is in the set. /// </summary> /// <param name="value">The value to test.</param> /// <returns>true if the set contains the specified value; otherwise, false.</returns> public bool Contains(T value) { return _dictionary.ContainsKey(value); } /// <summary> /// Attempts to add a value to the set. /// </summary> /// <param name="value">The value to add.</param> /// <returns>true if the value was added to the set. If the value already exists, this method returns false.</returns> public bool Add(T value) { return _dictionary.TryAdd(value, 0); } public void AddRange(IEnumerable<T>? values) { if (values != null) { foreach (var v in values) { Add(v); } } } /// <summary> /// Attempts to remove a value from the set. /// </summary> /// <param name="value">The value to remove.</param> /// <returns>true if the value was removed successfully; otherwise false.</returns> public bool Remove(T value) { return _dictionary.TryRemove(value, out _); } /// <summary> /// Clear the set /// </summary> public void Clear() { _dictionary.Clear(); } public struct KeyEnumerator { private readonly IEnumerator<KeyValuePair<T, byte>> _kvpEnumerator; internal KeyEnumerator(IEnumerable<KeyValuePair<T, byte>> data) { _kvpEnumerator = data.GetEnumerator(); } public T Current => _kvpEnumerator.Current.Key; public bool MoveNext() { return _kvpEnumerator.MoveNext(); } public void Reset() { _kvpEnumerator.Reset(); } } /// <summary> /// Obtain an enumerator that iterates through the elements in the set. /// </summary> /// <returns>An enumerator for the set.</returns> public KeyEnumerator GetEnumerator() { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. Instead, use the // KeyValuePair enumerator and pick off the Key part. return new KeyEnumerator(_dictionary); } private IEnumerator<T> GetEnumeratorImpl() { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. Instead, use the // KeyValuePair enumerator and pick off the Key part. foreach (var kvp in _dictionary) { yield return kvp.Key; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumeratorImpl(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorImpl(); } void ICollection<T>.Add(T item) { Add(item); } public void CopyTo(T[] array, int arrayIndex) { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. // Instead, enumerate the set and copy over the elements. foreach (var element in this) { array[arrayIndex++] = element; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; namespace Roslyn.Utilities { /// <summary> /// A concurrent, simplified HashSet. /// </summary> [DebuggerDisplay("Count = {Count}")] internal sealed class ConcurrentSet<T> : ICollection<T> where T : notnull { /// <summary> /// The default concurrency level is 2. That means the collection can cope with up to two /// threads making simultaneous modifications without blocking. /// Note ConcurrentDictionary's default concurrency level is dynamic, scaling according to /// the number of processors. /// </summary> private const int DefaultConcurrencyLevel = 2; /// <summary> /// Taken from ConcurrentDictionary.DEFAULT_CAPACITY /// </summary> private const int DefaultCapacity = 31; /// <summary> /// The backing dictionary. The values are never used; just the keys. /// </summary> private readonly ConcurrentDictionary<T, byte> _dictionary; /// <summary> /// Construct a concurrent set with the default concurrency level. /// </summary> public ConcurrentSet() { _dictionary = new ConcurrentDictionary<T, byte>(DefaultConcurrencyLevel, DefaultCapacity); } /// <summary> /// Construct a concurrent set using the specified equality comparer. /// </summary> /// <param name="equalityComparer">The equality comparer for values in the set.</param> public ConcurrentSet(IEqualityComparer<T> equalityComparer) { _dictionary = new ConcurrentDictionary<T, byte>(DefaultConcurrencyLevel, DefaultCapacity, equalityComparer); } /// <summary> /// Obtain the number of elements in the set. /// </summary> /// <returns>The number of elements in the set.</returns> public int Count => _dictionary.Count; /// <summary> /// Determine whether the set is empty.</summary> /// <returns>true if the set is empty; otherwise, false.</returns> public bool IsEmpty => _dictionary.IsEmpty; public bool IsReadOnly => false; /// <summary> /// Determine whether the given value is in the set. /// </summary> /// <param name="value">The value to test.</param> /// <returns>true if the set contains the specified value; otherwise, false.</returns> public bool Contains(T value) { return _dictionary.ContainsKey(value); } /// <summary> /// Attempts to add a value to the set. /// </summary> /// <param name="value">The value to add.</param> /// <returns>true if the value was added to the set. If the value already exists, this method returns false.</returns> public bool Add(T value) { return _dictionary.TryAdd(value, 0); } public void AddRange(IEnumerable<T>? values) { if (values != null) { foreach (var v in values) { Add(v); } } } /// <summary> /// Attempts to remove a value from the set. /// </summary> /// <param name="value">The value to remove.</param> /// <returns>true if the value was removed successfully; otherwise false.</returns> public bool Remove(T value) { return _dictionary.TryRemove(value, out _); } /// <summary> /// Clear the set /// </summary> public void Clear() { _dictionary.Clear(); } public struct KeyEnumerator { private readonly IEnumerator<KeyValuePair<T, byte>> _kvpEnumerator; internal KeyEnumerator(IEnumerable<KeyValuePair<T, byte>> data) { _kvpEnumerator = data.GetEnumerator(); } public T Current => _kvpEnumerator.Current.Key; public bool MoveNext() { return _kvpEnumerator.MoveNext(); } public void Reset() { _kvpEnumerator.Reset(); } } /// <summary> /// Obtain an enumerator that iterates through the elements in the set. /// </summary> /// <returns>An enumerator for the set.</returns> public KeyEnumerator GetEnumerator() { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. Instead, use the // KeyValuePair enumerator and pick off the Key part. return new KeyEnumerator(_dictionary); } private IEnumerator<T> GetEnumeratorImpl() { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. Instead, use the // KeyValuePair enumerator and pick off the Key part. foreach (var kvp in _dictionary) { yield return kvp.Key; } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumeratorImpl(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorImpl(); } void ICollection<T>.Add(T item) { Add(item); } public void CopyTo(T[] array, int arrayIndex) { // PERF: Do not use dictionary.Keys here because that creates a snapshot // of the collection resulting in a List<T> allocation. // Instead, enumerate the set and copy over the elements. foreach (var element in this) { array[arrayIndex++] = element; } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/AssemblyIdentityTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public abstract class AssemblyIdentityTestBase : TestBase { internal static readonly byte[] PublicKey1 = new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xb5, 0xfc, 0x90, 0xe7, 0x02, 0x7f, 0x67, 0x87, 0x1e, 0x77, 0x3a, 0x8f, 0xde, 0x89, 0x38, 0xc8, 0x1d, 0xd4, 0x02, 0xba, 0x65, 0xb9, 0x20, 0x1d, 0x60, 0x59, 0x3e, 0x96, 0xc4, 0x92, 0x65, 0x1e, 0x88, 0x9c, 0xc1, 0x3f, 0x14, 0x15, 0xeb, 0xb5, 0x3f, 0xac, 0x11, 0x31, 0xae, 0x0b, 0xd3, 0x33, 0xc5, 0xee, 0x60, 0x21, 0x67, 0x2d, 0x97, 0x18, 0xea, 0x31, 0xa8, 0xae, 0xbd, 0x0d, 0xa0, 0x07, 0x2f, 0x25, 0xd8, 0x7d, 0xba, 0x6f, 0xc9, 0x0f, 0xfd, 0x59, 0x8e, 0xd4, 0xda, 0x35, 0xe4, 0x4c, 0x39, 0x8c, 0x45, 0x43, 0x07, 0xe8, 0xe3, 0x3b, 0x84, 0x26, 0x14, 0x3d, 0xae, 0xc9, 0xf5, 0x96, 0x83, 0x6f, 0x97, 0xc8, 0xf7, 0x47, 0x50, 0xe5, 0x97, 0x5c, 0x64, 0xe2, 0x18, 0x9f, 0x45, 0xde, 0xf4, 0x6b, 0x2a, 0x2b, 0x12, 0x47, 0xad, 0xc3, 0x65, 0x2b, 0xf5, 0xc3, 0x08, 0x05, 0x5d, 0xa9 }; internal static readonly byte[] PublicKeyToken1 = new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }; internal static readonly string StrPublicKeyToken1 = ToDisplayString(PublicKeyToken1); internal static readonly string StrPublicKey1 = ToDisplayString(PublicKey1); internal static ImmutableArray<byte> RoPublicKey1 = PublicKey1.AsImmutableOrNull(); internal static ImmutableArray<byte> RoPublicKeyToken1 = PublicKeyToken1.AsImmutableOrNull(); internal static readonly HashSet<char> ClrInvalidCharacters = new HashSet<char> { '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u000b', '\u000c', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', }; internal static readonly HashSet<char> ClrBackslashEscapedCharacters = new HashSet<char> { ',', '/', '=', '\\' }; internal static string ToDisplayString(byte[] key) { StringBuilder sb = new StringBuilder(); foreach (byte b in key) { sb.Append(b.ToString("x2")); } return sb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.UnitTests { public abstract class AssemblyIdentityTestBase : TestBase { internal static readonly byte[] PublicKey1 = new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xb5, 0xfc, 0x90, 0xe7, 0x02, 0x7f, 0x67, 0x87, 0x1e, 0x77, 0x3a, 0x8f, 0xde, 0x89, 0x38, 0xc8, 0x1d, 0xd4, 0x02, 0xba, 0x65, 0xb9, 0x20, 0x1d, 0x60, 0x59, 0x3e, 0x96, 0xc4, 0x92, 0x65, 0x1e, 0x88, 0x9c, 0xc1, 0x3f, 0x14, 0x15, 0xeb, 0xb5, 0x3f, 0xac, 0x11, 0x31, 0xae, 0x0b, 0xd3, 0x33, 0xc5, 0xee, 0x60, 0x21, 0x67, 0x2d, 0x97, 0x18, 0xea, 0x31, 0xa8, 0xae, 0xbd, 0x0d, 0xa0, 0x07, 0x2f, 0x25, 0xd8, 0x7d, 0xba, 0x6f, 0xc9, 0x0f, 0xfd, 0x59, 0x8e, 0xd4, 0xda, 0x35, 0xe4, 0x4c, 0x39, 0x8c, 0x45, 0x43, 0x07, 0xe8, 0xe3, 0x3b, 0x84, 0x26, 0x14, 0x3d, 0xae, 0xc9, 0xf5, 0x96, 0x83, 0x6f, 0x97, 0xc8, 0xf7, 0x47, 0x50, 0xe5, 0x97, 0x5c, 0x64, 0xe2, 0x18, 0x9f, 0x45, 0xde, 0xf4, 0x6b, 0x2a, 0x2b, 0x12, 0x47, 0xad, 0xc3, 0x65, 0x2b, 0xf5, 0xc3, 0x08, 0x05, 0x5d, 0xa9 }; internal static readonly byte[] PublicKeyToken1 = new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }; internal static readonly string StrPublicKeyToken1 = ToDisplayString(PublicKeyToken1); internal static readonly string StrPublicKey1 = ToDisplayString(PublicKey1); internal static ImmutableArray<byte> RoPublicKey1 = PublicKey1.AsImmutableOrNull(); internal static ImmutableArray<byte> RoPublicKeyToken1 = PublicKeyToken1.AsImmutableOrNull(); internal static readonly HashSet<char> ClrInvalidCharacters = new HashSet<char> { '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u000b', '\u000c', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', }; internal static readonly HashSet<char> ClrBackslashEscapedCharacters = new HashSet<char> { ',', '/', '=', '\\' }; internal static string ToDisplayString(byte[] key) { StringBuilder sb = new StringBuilder(); foreach (byte b in key) { sb.Append(b.ToString("x2")); } return sb.ToString(); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/LoopHighlighter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class LoopHighlighter : AbstractKeywordHighlighter { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoopHighlighter() { } protected override bool IsHighlightableNode(SyntaxNode node) => node.IsContinuableConstruct(); protected override void AddHighlightsForNode( SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { switch (node) { case DoStatementSyntax doStatement: HighlightDoStatement(doStatement, spans); break; case ForStatementSyntax forStatement: HighlightForStatement(forStatement, spans); break; case CommonForEachStatementSyntax forEachStatement: HighlightForEachStatement(forEachStatement, spans); break; case WhileStatementSyntax whileStatement: HighlightWhileStatement(whileStatement, spans); break; } HighlightRelatedKeywords(node, spans, highlightBreaks: true, highlightContinues: true); } private static void HighlightDoStatement(DoStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.DoKeyword.Span); spans.Add(statement.WhileKeyword.Span); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); } private static void HighlightForStatement(ForStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForKeyword.Span); private static void HighlightForEachStatement(CommonForEachStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForEachKeyword.Span); private static void HighlightWhileStatement(WhileStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.WhileKeyword.Span); /// <summary> /// Finds all breaks and continues that are a child of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans, bool highlightBreaks, bool highlightContinues) { Debug.Assert(highlightBreaks || highlightContinues); if (highlightBreaks && node is BreakStatementSyntax breakStatement) { spans.Add(breakStatement.BreakKeyword.Span); spans.Add(EmptySpan(breakStatement.SemicolonToken.Span.End)); } else if (highlightContinues && node is ContinueStatementSyntax continueStatement) { spans.Add(continueStatement.ContinueKeyword.Span); spans.Add(EmptySpan(continueStatement.SemicolonToken.Span.End)); } else { foreach (var child in node.ChildNodes()) { var highlightBreaksForChild = highlightBreaks && !child.IsBreakableConstruct(); var highlightContinuesForChild = highlightContinues && !child.IsContinuableConstruct(); // Only recurse if we have anything to do if (highlightBreaksForChild || highlightContinuesForChild) { HighlightRelatedKeywords(child, spans, highlightBreaksForChild, highlightContinuesForChild); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class LoopHighlighter : AbstractKeywordHighlighter { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public LoopHighlighter() { } protected override bool IsHighlightableNode(SyntaxNode node) => node.IsContinuableConstruct(); protected override void AddHighlightsForNode( SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { switch (node) { case DoStatementSyntax doStatement: HighlightDoStatement(doStatement, spans); break; case ForStatementSyntax forStatement: HighlightForStatement(forStatement, spans); break; case CommonForEachStatementSyntax forEachStatement: HighlightForEachStatement(forEachStatement, spans); break; case WhileStatementSyntax whileStatement: HighlightWhileStatement(whileStatement, spans); break; } HighlightRelatedKeywords(node, spans, highlightBreaks: true, highlightContinues: true); } private static void HighlightDoStatement(DoStatementSyntax statement, List<TextSpan> spans) { spans.Add(statement.DoKeyword.Span); spans.Add(statement.WhileKeyword.Span); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); } private static void HighlightForStatement(ForStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForKeyword.Span); private static void HighlightForEachStatement(CommonForEachStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.ForEachKeyword.Span); private static void HighlightWhileStatement(WhileStatementSyntax statement, List<TextSpan> spans) => spans.Add(statement.WhileKeyword.Span); /// <summary> /// Finds all breaks and continues that are a child of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans, bool highlightBreaks, bool highlightContinues) { Debug.Assert(highlightBreaks || highlightContinues); if (highlightBreaks && node is BreakStatementSyntax breakStatement) { spans.Add(breakStatement.BreakKeyword.Span); spans.Add(EmptySpan(breakStatement.SemicolonToken.Span.End)); } else if (highlightContinues && node is ContinueStatementSyntax continueStatement) { spans.Add(continueStatement.ContinueKeyword.Span); spans.Add(EmptySpan(continueStatement.SemicolonToken.Span.End)); } else { foreach (var child in node.ChildNodes()) { var highlightBreaksForChild = highlightBreaks && !child.IsBreakableConstruct(); var highlightContinuesForChild = highlightContinues && !child.IsContinuableConstruct(); // Only recurse if we have anything to do if (highlightBreaksForChild || highlightContinuesForChild) { HighlightRelatedKeywords(child, spans, highlightBreaksForChild, highlightContinuesForChild); } } } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/VisualBasic/Portable/ConvertCast/VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider.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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertCast Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), [Shared]> Friend Class VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider Inherits AbstractConvertCastCodeRefactoringProvider(Of TypeSyntax, TryCastExpressionSyntax, DirectCastExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Change_to_DirectCast End Function Protected Overrides ReadOnly Property FromKind As Integer = SyntaxKind.TryCastExpression Protected Overrides Function GetTypeNode(from As TryCastExpressionSyntax) As TypeSyntax Return from.Type End Function Protected Overrides Function ConvertExpression(fromExpression As TryCastExpressionSyntax) As DirectCastExpressionSyntax Return SyntaxFactory.DirectCastExpression( SyntaxFactory.Token(SyntaxKind.DirectCastKeyword), fromExpression.OpenParenToken, fromExpression.Expression, fromExpression.CommaToken, fromExpression.Type, fromExpression.CloseParenToken) 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertCast Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertConversionOperators <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertTryCastToDirectCast), [Shared]> Friend Class VisualBasicConvertTryCastToDirectCastCodeRefactoringProvider Inherits AbstractConvertCastCodeRefactoringProvider(Of TypeSyntax, TryCastExpressionSyntax, DirectCastExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Change_to_DirectCast End Function Protected Overrides ReadOnly Property FromKind As Integer = SyntaxKind.TryCastExpression Protected Overrides Function GetTypeNode(from As TryCastExpressionSyntax) As TypeSyntax Return from.Type End Function Protected Overrides Function ConvertExpression(fromExpression As TryCastExpressionSyntax) As DirectCastExpressionSyntax Return SyntaxFactory.DirectCastExpression( SyntaxFactory.Token(SyntaxKind.DirectCastKeyword), fromExpression.OpenParenToken, fromExpression.Expression, fromExpression.CommaToken, fromExpression.Type, fromExpression.CloseParenToken) End Function End Class End Namespace
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/TextSpanIntervalIntrospector.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.Shared.Collections { internal readonly struct TextSpanIntervalIntrospector : IIntervalIntrospector<TextSpan> { public int GetStart(TextSpan value) => value.Start; public int GetLength(TextSpan value) => value.Length; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared.Collections { internal readonly struct TextSpanIntervalIntrospector : IIntervalIntrospector<TextSpan> { public int GetStart(TextSpan value) => value.Start; public int GetLength(TextSpan value) => value.Length; } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/EditorFeatures/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitOrMergeIfStatements { [Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)] public sealed class SplitIntoNestedIfStatementsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpSplitIntoNestedIfStatementsCodeRefactoringProvider(); [Theory] [InlineData("a [||]&& b")] [InlineData("a &[||]& b")] [InlineData("a &&[||] b")] [InlineData("a [|&&|] b")] public async Task SplitOnAndOperatorSpans(string condition) { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (" + condition + @") { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) { } } } }"); } [Theory] [InlineData("a [|&|]& b")] [InlineData("a[| &&|] b")] [InlineData("a[||] && b")] public async Task NotSplitOnAndOperatorSpans(string condition) { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (" + condition + @") { } } }"); } [Fact] public async Task NotSplitOnIfKeyword() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { [||]if (a && b) { } } }"); } [Fact] public async Task NotSplitOnOrOperator() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]|| b) { } } }"); } [Fact] public async Task NotSplitOnBitwiseAndOperator() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]& b) { } } }"); } [Fact] public async Task NotSplitOnAndOperatorOutsideIfStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { var v = a [||]&& b; } }"); } [Fact] public async Task NotSplitOnAndOperatorInIfStatementBody() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a && b) a [||]&& b; } }"); } [Fact] public async Task SplitWithChainedAndExpression1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a [||]&& b && c && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a) { if (b && c && d) { } } } }"); } [Fact] public async Task SplitWithChainedAndExpression2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b [||]&& c && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b) { if (c && d) { } } } }"); } [Fact] public async Task SplitWithChainedAndExpression3() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && c [||]&& d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && c) { if (d) { } } } }"); } [Fact] public async Task NotSplitInsideParentheses1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if ((a [||]&& b) && c && d) { } } }"); } [Fact] public async Task NotSplitInsideParentheses2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && (c [||]&& d)) { } } }"); } [Fact] public async Task NotSplitInsideParentheses3() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if ((a && b [||]&& c && d)) { } } }"); } [Fact] public async Task SplitWithOtherExpressionInsideParentheses1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a [||]&& (b && c) && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a) { if ((b && c) && d) { } } } }"); } [Fact] public async Task SplitWithOtherExpressionInsideParentheses2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && (b && c) [||]&& d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && (b && c)) { if (d) { } } } }"); } [Fact] public async Task NotSplitWithMixedOrExpression1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& b || c) { } } }"); } [Fact] public async Task NotSplitWithMixedOrExpression2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a || b [||]&& c) { } } }"); } [Fact] public async Task SplitWithMixedOrExpressionInsideParentheses1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& (b || c)) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a) { if ((b || c)) { } } } }"); } [Fact] public async Task SplitWithMixedOrExpressionInsideParentheses2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if ((a || b) [||]&& c) { } } }", @"class C { void M(bool a, bool b, bool c) { if ((a || b)) { if (c) { } } } }"); } [Fact] public async Task SplitWithMixedBitwiseOrExpression1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& b | c) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a) { if (b | c) { } } } }"); } [Fact] public async Task SplitWithMixedBitwiseOrExpression2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a | b [||]&& c) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a | b) { if (c) { } } } }"); } [Fact] public async Task SplitWithStatementInsideBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) { System.Console.WriteLine(a && b); } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) { System.Console.WriteLine(a && b); } } } }"); } [Fact] public async Task SplitWithStatementWithoutBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(a && b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(a && b); } } }"); } [Fact] public async Task SplitWithNestedIfStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) if (true) { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) if (true) { } } } }"); } [Fact] public async Task SplitWithMissingStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) } }", @"class C { void M(bool a, bool b) { if (a) { if (b) } } }"); } [Fact] public async Task SplitWithElseStatementInsideBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else { System.Console.WriteLine(a && b); } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else { System.Console.WriteLine(a && b); } } else { System.Console.WriteLine(a && b); } } }"); } [Fact] public async Task SplitWithElseStatementWithoutBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else System.Console.WriteLine(a && b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else System.Console.WriteLine(a && b); } else System.Console.WriteLine(a && b); } }"); } [Fact] public async Task SplitWithElseNestedIfStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else if (true) { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else if (true) { } } else if (true) { } } }"); } [Fact] public async Task SplitWithElseIfElse() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }"); } [Fact] public async Task SplitAsPartOfElseIfElse() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (true) System.Console.WriteLine(); else if (a [||]&& b) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }", @"class C { void M(bool a, bool b) { if (true) System.Console.WriteLine(); else if (a) { if (b) System.Console.WriteLine(a); else System.Console.WriteLine(b); } else System.Console.WriteLine(b); } }"); } [Fact] public async Task SplitWithMissingElseStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else } else } }"); } [Fact] public async Task SplitWithPreservedSingleLineFormatting() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitOrMergeIfStatements { [Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)] public sealed class SplitIntoNestedIfStatementsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpSplitIntoNestedIfStatementsCodeRefactoringProvider(); [Theory] [InlineData("a [||]&& b")] [InlineData("a &[||]& b")] [InlineData("a &&[||] b")] [InlineData("a [|&&|] b")] public async Task SplitOnAndOperatorSpans(string condition) { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (" + condition + @") { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) { } } } }"); } [Theory] [InlineData("a [|&|]& b")] [InlineData("a[| &&|] b")] [InlineData("a[||] && b")] public async Task NotSplitOnAndOperatorSpans(string condition) { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (" + condition + @") { } } }"); } [Fact] public async Task NotSplitOnIfKeyword() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { [||]if (a && b) { } } }"); } [Fact] public async Task NotSplitOnOrOperator() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]|| b) { } } }"); } [Fact] public async Task NotSplitOnBitwiseAndOperator() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]& b) { } } }"); } [Fact] public async Task NotSplitOnAndOperatorOutsideIfStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { var v = a [||]&& b; } }"); } [Fact] public async Task NotSplitOnAndOperatorInIfStatementBody() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a && b) a [||]&& b; } }"); } [Fact] public async Task SplitWithChainedAndExpression1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a [||]&& b && c && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a) { if (b && c && d) { } } } }"); } [Fact] public async Task SplitWithChainedAndExpression2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b [||]&& c && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b) { if (c && d) { } } } }"); } [Fact] public async Task SplitWithChainedAndExpression3() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && c [||]&& d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && c) { if (d) { } } } }"); } [Fact] public async Task NotSplitInsideParentheses1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if ((a [||]&& b) && c && d) { } } }"); } [Fact] public async Task NotSplitInsideParentheses2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && b && (c [||]&& d)) { } } }"); } [Fact] public async Task NotSplitInsideParentheses3() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if ((a && b [||]&& c && d)) { } } }"); } [Fact] public async Task SplitWithOtherExpressionInsideParentheses1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a [||]&& (b && c) && d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a) { if ((b && c) && d) { } } } }"); } [Fact] public async Task SplitWithOtherExpressionInsideParentheses2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c, bool d) { if (a && (b && c) [||]&& d) { } } }", @"class C { void M(bool a, bool b, bool c, bool d) { if (a && (b && c)) { if (d) { } } } }"); } [Fact] public async Task NotSplitWithMixedOrExpression1() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& b || c) { } } }"); } [Fact] public async Task NotSplitWithMixedOrExpression2() { await TestMissingInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a || b [||]&& c) { } } }"); } [Fact] public async Task SplitWithMixedOrExpressionInsideParentheses1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& (b || c)) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a) { if ((b || c)) { } } } }"); } [Fact] public async Task SplitWithMixedOrExpressionInsideParentheses2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if ((a || b) [||]&& c) { } } }", @"class C { void M(bool a, bool b, bool c) { if ((a || b)) { if (c) { } } } }"); } [Fact] public async Task SplitWithMixedBitwiseOrExpression1() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a [||]&& b | c) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a) { if (b | c) { } } } }"); } [Fact] public async Task SplitWithMixedBitwiseOrExpression2() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b, bool c) { if (a | b [||]&& c) { } } }", @"class C { void M(bool a, bool b, bool c) { if (a | b) { if (c) { } } } }"); } [Fact] public async Task SplitWithStatementInsideBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) { System.Console.WriteLine(a && b); } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) { System.Console.WriteLine(a && b); } } } }"); } [Fact] public async Task SplitWithStatementWithoutBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(a && b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(a && b); } } }"); } [Fact] public async Task SplitWithNestedIfStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) if (true) { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) if (true) { } } } }"); } [Fact] public async Task SplitWithMissingStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) } }", @"class C { void M(bool a, bool b) { if (a) { if (b) } } }"); } [Fact] public async Task SplitWithElseStatementInsideBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else { System.Console.WriteLine(a && b); } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else { System.Console.WriteLine(a && b); } } else { System.Console.WriteLine(a && b); } } }"); } [Fact] public async Task SplitWithElseStatementWithoutBlock() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else System.Console.WriteLine(a && b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else System.Console.WriteLine(a && b); } else System.Console.WriteLine(a && b); } }"); } [Fact] public async Task SplitWithElseNestedIfStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else if (true) { } } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else if (true) { } } else if (true) { } } }"); } [Fact] public async Task SplitWithElseIfElse() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } else if (a) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }"); } [Fact] public async Task SplitAsPartOfElseIfElse() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (true) System.Console.WriteLine(); else if (a [||]&& b) System.Console.WriteLine(a); else System.Console.WriteLine(b); } }", @"class C { void M(bool a, bool b) { if (true) System.Console.WriteLine(); else if (a) { if (b) System.Console.WriteLine(a); else System.Console.WriteLine(b); } else System.Console.WriteLine(b); } }"); } [Fact] public async Task SplitWithMissingElseStatement() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); else } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); else } else } }"); } [Fact] public async Task SplitWithPreservedSingleLineFormatting() { await TestInRegularAndScriptAsync( @"class C { void M(bool a, bool b) { if (a [||]&& b) System.Console.WriteLine(); } }", @"class C { void M(bool a, bool b) { if (a) { if (b) System.Console.WriteLine(); } } }"); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/Remote/Core/SolutionAssetStorage.Scope.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal partial class SolutionAssetStorage { internal readonly struct Scope : IDisposable { private readonly SolutionAssetStorage _storages; public readonly PinnedSolutionInfo SolutionInfo; public Scope(SolutionAssetStorage storages, PinnedSolutionInfo solutionInfo) { _storages = storages; SolutionInfo = solutionInfo; } public void Dispose() { Contract.ThrowIfFalse(_storages._solutionStates.TryRemove(SolutionInfo.ScopeId, out var entry)); entry.ReplicationContext.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal partial class SolutionAssetStorage { internal readonly struct Scope : IDisposable { private readonly SolutionAssetStorage _storages; public readonly PinnedSolutionInfo SolutionInfo; public Scope(SolutionAssetStorage storages, PinnedSolutionInfo solutionInfo) { _storages = storages; SolutionInfo = solutionInfo; } public void Dispose() { Contract.ThrowIfFalse(_storages._solutionStates.TryRemove(SolutionInfo.ScopeId, out var entry)); entry.ReplicationContext.Dispose(); } } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/VisualBasic/Portable/Symbols/MetadataOrSourceAssemblySymbol.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.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents source or metadata assembly. ''' </summary> ''' <remarks></remarks> Friend MustInherit Class MetadataOrSourceAssemblySymbol Inherits NonMissingAssemblySymbol ''' <summary> ''' An array of cached Cor types defined in this assembly. ''' Lazily filled by GetSpecialType method. ''' </summary> ''' <remarks></remarks> Private _lazySpecialTypes() As NamedTypeSymbol ''' <summary> ''' How many Cor types have we cached so far. ''' </summary> Private _cachedSpecialTypes As Integer ''' <summary> ''' Lookup declaration for predefined CorLib type in this Assembly. Only should be ''' called if it is know that this is the Cor Library (mscorlib). ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol #If DEBUG Then For Each [module] In Me.Modules Debug.Assert([module].GetReferencedAssemblies().Length = 0) Next #End If If _lazySpecialTypes Is Nothing OrElse _lazySpecialTypes(type) Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim [module] As ModuleSymbol = Me.Modules(0) Dim result As NamedTypeSymbol = [module].LookupTopLevelMetadataType(emittedName) If result.TypeKind <> TypeKind.Error AndAlso result.DeclaredAccessibility <> Accessibility.Public Then result = New MissingMetadataTypeSymbol.TopLevel([module], emittedName, type) End If RegisterDeclaredSpecialType(result) End If Return _lazySpecialTypes(type) End Function ''' <summary> ''' Register declaration of predefined CorLib type in this Assembly. ''' </summary> ''' <param name="corType"></param> Friend Overrides Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol) Dim typeId As SpecialType = corType.SpecialType Debug.Assert(typeId <> SpecialType.None) Debug.Assert(corType.ContainingAssembly Is Me) Debug.Assert(corType.ContainingModule.Ordinal = 0) Debug.Assert(Me.CorLibrary Is Me) If (_lazySpecialTypes Is Nothing) Then Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing) End If If (Interlocked.CompareExchange(_lazySpecialTypes(typeId), corType, Nothing) IsNot Nothing) Then Debug.Assert(corType Is _lazySpecialTypes(typeId) OrElse (corType.Kind = SymbolKind.ErrorType AndAlso _lazySpecialTypes(typeId).Kind = SymbolKind.ErrorType)) Else Interlocked.Increment(_cachedSpecialTypes) Debug.Assert(_cachedSpecialTypes > 0 AndAlso _cachedSpecialTypes <= SpecialType.Count) End If End Sub ''' <summary> ''' Continue looking for declaration of predefined CorLib type in this Assembly ''' while symbols for new type declarations are constructed. ''' </summary> Friend Overrides ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean Get Return Me.CorLibrary Is Me AndAlso _cachedSpecialTypes < SpecialType.Count End Get End Property Private _lazyTypeNames As ICollection(Of String) Private _lazyNamespaceNames As ICollection(Of String) Public Overrides ReadOnly Property TypeNames As ICollection(Of String) Get If _lazyTypeNames Is Nothing Then Interlocked.CompareExchange(_lazyTypeNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.TypeNames), Nothing) End If Return _lazyTypeNames End Get End Property Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String) Get If _lazyNamespaceNames Is Nothing Then Interlocked.CompareExchange(_lazyNamespaceNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.NamespaceNames), Nothing) End If Return _lazyNamespaceNames End Get End Property ''' <summary> ''' Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. ''' Assumes that the public key has been determined. The result will be cached. ''' </summary> ''' <param name="potentialGiverOfAccess"></param> ''' <returns></returns> ''' <remarks></remarks> Protected Function MakeFinalIVTDetermination(potentialGiverOfAccess As AssemblySymbol) As IVTConclusion Dim result As IVTConclusion = IVTConclusion.NoRelationshipClaimed If AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, result) Then Return result End If result = IVTConclusion.NoRelationshipClaimed ' returns an empty list if there was no IVT attribute at all for the given name ' A name w/o a key is represented by a list with an entry that is empty Dim publicKeys As IEnumerable(Of ImmutableArray(Of Byte)) = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Me.Name) ' We have an easy out here. Suppose the assembly wanting access is ' being compiled as a module. You can only strong-name an assembly. So we are going to optimistically ' assume that it Is going to be compiled into an assembly with a matching strong name, if necessary If publicKeys.Any() AndAlso IsNetModule Then Return IVTConclusion.Match End If ' look for one that works, if none work, then return the failure for the last one examined. For Each key In publicKeys ' We pass the public key of this assembly explicitly so PerformIVTCheck does not need ' to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(Me.PublicKey, key) If result = IVTConclusion.Match Then ' Note that C# includes OrElse result = IVTConclusion.OneSignedOneNot Exit For End If Next AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result) Return result End Function 'EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant 'internals access to us to the conclusion reached. Private _assembliesToWhichInternalAccessHasBeenAnalyzed As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Private ReadOnly Property AssembliesToWhichInternalAccessHasBeenDetermined As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Get If _assembliesToWhichInternalAccessHasBeenAnalyzed Is Nothing Then Interlocked.CompareExchange(_assembliesToWhichInternalAccessHasBeenAnalyzed, New ConcurrentDictionary(Of AssemblySymbol, IVTConclusion), Nothing) End If Return _assembliesToWhichInternalAccessHasBeenAnalyzed End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents source or metadata assembly. ''' </summary> ''' <remarks></remarks> Friend MustInherit Class MetadataOrSourceAssemblySymbol Inherits NonMissingAssemblySymbol ''' <summary> ''' An array of cached Cor types defined in this assembly. ''' Lazily filled by GetSpecialType method. ''' </summary> ''' <remarks></remarks> Private _lazySpecialTypes() As NamedTypeSymbol ''' <summary> ''' How many Cor types have we cached so far. ''' </summary> Private _cachedSpecialTypes As Integer ''' <summary> ''' Lookup declaration for predefined CorLib type in this Assembly. Only should be ''' called if it is know that this is the Cor Library (mscorlib). ''' </summary> ''' <param name="type"></param> ''' <returns></returns> ''' <remarks></remarks> Friend Overrides Function GetDeclaredSpecialType(type As SpecialType) As NamedTypeSymbol #If DEBUG Then For Each [module] In Me.Modules Debug.Assert([module].GetReferencedAssemblies().Length = 0) Next #End If If _lazySpecialTypes Is Nothing OrElse _lazySpecialTypes(type) Is Nothing Then Dim emittedName As MetadataTypeName = MetadataTypeName.FromFullName(SpecialTypes.GetMetadataName(type), useCLSCompliantNameArityEncoding:=True) Dim [module] As ModuleSymbol = Me.Modules(0) Dim result As NamedTypeSymbol = [module].LookupTopLevelMetadataType(emittedName) If result.TypeKind <> TypeKind.Error AndAlso result.DeclaredAccessibility <> Accessibility.Public Then result = New MissingMetadataTypeSymbol.TopLevel([module], emittedName, type) End If RegisterDeclaredSpecialType(result) End If Return _lazySpecialTypes(type) End Function ''' <summary> ''' Register declaration of predefined CorLib type in this Assembly. ''' </summary> ''' <param name="corType"></param> Friend Overrides Sub RegisterDeclaredSpecialType(corType As NamedTypeSymbol) Dim typeId As SpecialType = corType.SpecialType Debug.Assert(typeId <> SpecialType.None) Debug.Assert(corType.ContainingAssembly Is Me) Debug.Assert(corType.ContainingModule.Ordinal = 0) Debug.Assert(Me.CorLibrary Is Me) If (_lazySpecialTypes Is Nothing) Then Interlocked.CompareExchange(_lazySpecialTypes, New NamedTypeSymbol(SpecialType.Count) {}, Nothing) End If If (Interlocked.CompareExchange(_lazySpecialTypes(typeId), corType, Nothing) IsNot Nothing) Then Debug.Assert(corType Is _lazySpecialTypes(typeId) OrElse (corType.Kind = SymbolKind.ErrorType AndAlso _lazySpecialTypes(typeId).Kind = SymbolKind.ErrorType)) Else Interlocked.Increment(_cachedSpecialTypes) Debug.Assert(_cachedSpecialTypes > 0 AndAlso _cachedSpecialTypes <= SpecialType.Count) End If End Sub ''' <summary> ''' Continue looking for declaration of predefined CorLib type in this Assembly ''' while symbols for new type declarations are constructed. ''' </summary> Friend Overrides ReadOnly Property KeepLookingForDeclaredSpecialTypes As Boolean Get Return Me.CorLibrary Is Me AndAlso _cachedSpecialTypes < SpecialType.Count End Get End Property Private _lazyTypeNames As ICollection(Of String) Private _lazyNamespaceNames As ICollection(Of String) Public Overrides ReadOnly Property TypeNames As ICollection(Of String) Get If _lazyTypeNames Is Nothing Then Interlocked.CompareExchange(_lazyTypeNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.TypeNames), Nothing) End If Return _lazyTypeNames End Get End Property Public Overrides ReadOnly Property NamespaceNames As ICollection(Of String) Get If _lazyNamespaceNames Is Nothing Then Interlocked.CompareExchange(_lazyNamespaceNames, UnionCollection(Of String).Create(Me.Modules, Function(m) m.NamespaceNames), Nothing) End If Return _lazyNamespaceNames End Get End Property ''' <summary> ''' Determine whether this assembly has been granted access to <paramref name="potentialGiverOfAccess"></paramref>. ''' Assumes that the public key has been determined. The result will be cached. ''' </summary> ''' <param name="potentialGiverOfAccess"></param> ''' <returns></returns> ''' <remarks></remarks> Protected Function MakeFinalIVTDetermination(potentialGiverOfAccess As AssemblySymbol) As IVTConclusion Dim result As IVTConclusion = IVTConclusion.NoRelationshipClaimed If AssembliesToWhichInternalAccessHasBeenDetermined.TryGetValue(potentialGiverOfAccess, result) Then Return result End If result = IVTConclusion.NoRelationshipClaimed ' returns an empty list if there was no IVT attribute at all for the given name ' A name w/o a key is represented by a list with an entry that is empty Dim publicKeys As IEnumerable(Of ImmutableArray(Of Byte)) = potentialGiverOfAccess.GetInternalsVisibleToPublicKeys(Me.Name) ' We have an easy out here. Suppose the assembly wanting access is ' being compiled as a module. You can only strong-name an assembly. So we are going to optimistically ' assume that it Is going to be compiled into an assembly with a matching strong name, if necessary If publicKeys.Any() AndAlso IsNetModule Then Return IVTConclusion.Match End If ' look for one that works, if none work, then return the failure for the last one examined. For Each key In publicKeys ' We pass the public key of this assembly explicitly so PerformIVTCheck does not need ' to get it from this.Identity, which would trigger an infinite recursion. result = potentialGiverOfAccess.Identity.PerformIVTCheck(Me.PublicKey, key) If result = IVTConclusion.Match Then ' Note that C# includes OrElse result = IVTConclusion.OneSignedOneNot Exit For End If Next AssembliesToWhichInternalAccessHasBeenDetermined.TryAdd(potentialGiverOfAccess, result) Return result End Function 'EDMAURER This is a cache mapping from assemblies which we have analyzed whether or not they grant 'internals access to us to the conclusion reached. Private _assembliesToWhichInternalAccessHasBeenAnalyzed As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Private ReadOnly Property AssembliesToWhichInternalAccessHasBeenDetermined As ConcurrentDictionary(Of AssemblySymbol, IVTConclusion) Get If _assembliesToWhichInternalAccessHasBeenAnalyzed Is Nothing Then Interlocked.CompareExchange(_assembliesToWhichInternalAccessHasBeenAnalyzed, New ConcurrentDictionary(Of AssemblySymbol, IVTConclusion), Nothing) End If Return _assembliesToWhichInternalAccessHasBeenAnalyzed End Get End Property End Class End Namespace
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBWinMdExpTests.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 Roslyn.Test.Utilities Imports System.IO Imports System.Text Imports System.Xml Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBWinMdExpTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Empty() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map/> AssertEqual(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Basic() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="3" start-column="8" end-line="3" end-column="15"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="9" end-line="4" end-column="13"/> </token-map> AssertEqual(expected, actual) End Sub <WorkItem(693206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/693206")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug693206() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Module Module1 Enum E One End Enum End Module End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="12" end-line="4" end-column="19"/> <token-location token="0x02xxxxxx" file="a.vb" start-line="5" start-column="14" end-line="5" end-column="15"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="5" start-column="14" end-line="5" end-column="15"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="6" start-column="13" end-line="6" end-column="16"/> </token-map> AssertEqual(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Property_Event() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Public Delegate Sub D(i As Integer) Public Class Bar Shared Sub New() End Sub Sub New(i As Integer) End Sub Public Event E As D Public Event E2 As action Public Property P As Integer Public Property P2 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Default Public Property P3(i As Integer) As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property End Class End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( source, LatestVbReferences, options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) CompilationUtils.AssertNoDiagnostics(compilation) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x02xxxxxx" file="a.vb" start-line="6" start-column="18" end-line="6" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="7" start-column="20" end-line="7" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="10" start-column="13" end-line="10" end-column="16"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x14xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x14xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="18" start-column="25" end-line="18" end-column="27"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="19" start-column="13" end-line="19" end-column="16"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="22" start-column="13" end-line="22" end-column="16"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="26" start-column="33" end-line="26" end-column="35"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="27" start-column="13" end-line="27" end-column="16"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="30" start-column="13" end-line="30" end-column="16"/> </token-map> AssertEqual(expected, actual) End Sub Private Shared Sub AssertEqual(expected As System.Xml.Linq.XDocument, actual As String) Dim builder As New StringBuilder Dim writer As New System.Xml.XmlTextWriter(New StringWriter(builder)) writer.Formatting = Formatting.Indented expected.WriteTo(writer) Assert.Equal(builder.ToString(), actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_AnonymousTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Public Class Bar Public Shared Sub S() Dim a = New With { .x = 1, .y = New With { .a = 1 } } Dim b = New With { .t = New With { .t = New With { .t = New With { .t = New With { .a = 1 } } } } } End Sub End Class End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="18" end-line="4" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="18" end-line="4" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="5" start-column="27" end-line="5" end-column="28"/> </token-map> AssertEqual(expected, actual) 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 Roslyn.Test.Utilities Imports System.IO Imports System.Text Imports System.Xml Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBWinMdExpTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Empty() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map/> AssertEqual(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Basic() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main(args As String()) Dim x As Integer = 0 Do While x < 5 If x < 1 Then Console.WriteLine("<1") ElseIf x < 2 Then Dim s2 As String = "<2" Console.WriteLine(s2) ElseIf x < 3 Then Dim s3 As String = "<3" Console.WriteLine(s3) Else Dim e1 As String = "Else" Console.WriteLine(e1) End If Dim newX As Integer = x + 1 x = newX Loop End Sub End Module ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="3" start-column="8" end-line="3" end-column="15"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="9" end-line="4" end-column="13"/> </token-map> AssertEqual(expected, actual) End Sub <WorkItem(693206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/693206")> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub Bug693206() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Module Module1 Enum E One End Enum End Module End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="12" end-line="4" end-column="19"/> <token-location token="0x02xxxxxx" file="a.vb" start-line="5" start-column="14" end-line="5" end-column="15"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="5" start-column="14" end-line="5" end-column="15"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="6" start-column="13" end-line="6" end-column="16"/> </token-map> AssertEqual(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_Property_Event() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Public Delegate Sub D(i As Integer) Public Class Bar Shared Sub New() End Sub Sub New(i As Integer) End Sub Public Event E As D Public Event E2 As action Public Property P As Integer Public Property P2 As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property Default Public Property P3(i As Integer) As Integer Get Return Nothing End Get Set(value As Integer) End Set End Property End Class End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences( source, LatestVbReferences, options:=TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) CompilationUtils.AssertNoDiagnostics(compilation) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="25" end-line="4" end-column="26"/> <token-location token="0x02xxxxxx" file="a.vb" start-line="6" start-column="18" end-line="6" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="7" start-column="20" end-line="7" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="10" start-column="13" end-line="10" end-column="16"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x14xxxxxx" file="a.vb" start-line="13" start-column="22" end-line="13" end-column="23"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x14xxxxxx" file="a.vb" start-line="14" start-column="22" end-line="14" end-column="24"/> <token-location token="0x04xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="16" start-column="25" end-line="16" end-column="26"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="18" start-column="25" end-line="18" end-column="27"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="19" start-column="13" end-line="19" end-column="16"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="22" start-column="13" end-line="22" end-column="16"/> <token-location token="0x17xxxxxx" file="a.vb" start-line="26" start-column="33" end-line="26" end-column="35"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="27" start-column="13" end-line="27" end-column="16"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="30" start-column="13" end-line="30" end-column="16"/> </token-map> AssertEqual(expected, actual) End Sub Private Shared Sub AssertEqual(expected As System.Xml.Linq.XDocument, actual As String) Dim builder As New StringBuilder Dim writer As New System.Xml.XmlTextWriter(New StringWriter(builder)) writer.Formatting = Formatting.Indented expected.WriteTo(writer) Assert.Equal(builder.ToString(), actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub TestWinMdExpData_AnonymousTypes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace X Public Class Bar Public Shared Sub S() Dim a = New With { .x = 1, .y = New With { .a = 1 } } Dim b = New With { .t = New With { .t = New With { .t = New With { .t = New With { .a = 1 } } } } } End Sub End Class End Namespace ]]></file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata)) Dim actual = PdbTestUtilities.GetTokenToLocationMap(compilation, True) Dim expected = <?xml version="1.0" encoding="utf-16"?> <token-map> <token-location token="0x02xxxxxx" file="a.vb" start-line="4" start-column="18" end-line="4" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="4" start-column="18" end-line="4" end-column="21"/> <token-location token="0x06xxxxxx" file="a.vb" start-line="5" start-column="27" end-line="5" end-column="28"/> </token-map> AssertEqual(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/ConcatImmutableArray`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal readonly struct ConcatImmutableArray<T> : IEnumerable<T> { private readonly ImmutableArray<T> _first; private readonly ImmutableArray<T> _second; public ConcatImmutableArray(ImmutableArray<T> first, ImmutableArray<T> second) { _first = first; _second = second; } public int Length => _first.Length + _second.Length; public bool Any(Func<T, bool> predicate) => _first.Any(predicate) || _second.Any(predicate); public Enumerator GetEnumerator() => new(_first, _second); public ImmutableArray<T> ToImmutableArray() => _first.NullToEmpty().AddRange(_second.NullToEmpty()); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<T> { private ImmutableArray<T>.Enumerator _current; private ImmutableArray<T> _next; public Enumerator(ImmutableArray<T> first, ImmutableArray<T> second) { _current = first.NullToEmpty().GetEnumerator(); _next = second.NullToEmpty(); } public T Current => _current.Current; object? IEnumerator.Current => Current; public bool MoveNext() { if (_current.MoveNext()) { return true; } _current = _next.GetEnumerator(); _next = ImmutableArray<T>.Empty; return _current.MoveNext(); } void IDisposable.Dispose() { } void IEnumerator.Reset() => throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal readonly struct ConcatImmutableArray<T> : IEnumerable<T> { private readonly ImmutableArray<T> _first; private readonly ImmutableArray<T> _second; public ConcatImmutableArray(ImmutableArray<T> first, ImmutableArray<T> second) { _first = first; _second = second; } public int Length => _first.Length + _second.Length; public bool Any(Func<T, bool> predicate) => _first.Any(predicate) || _second.Any(predicate); public Enumerator GetEnumerator() => new(_first, _second); public ImmutableArray<T> ToImmutableArray() => _first.NullToEmpty().AddRange(_second.NullToEmpty()); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public struct Enumerator : IEnumerator<T> { private ImmutableArray<T>.Enumerator _current; private ImmutableArray<T> _next; public Enumerator(ImmutableArray<T> first, ImmutableArray<T> second) { _current = first.NullToEmpty().GetEnumerator(); _next = second.NullToEmpty(); } public T Current => _current.Current; object? IEnumerator.Current => Current; public bool MoveNext() { if (_current.MoveNext()) { return true; } _current = _next.GetEnumerator(); _next = ImmutableArray<T>.Empty; return _current.MoveNext(); } void IDisposable.Dispose() { } void IEnumerator.Reset() => throw new NotSupportedException(); } } }
-1
dotnet/roslyn
54,967
Call EnsureSufficientExecutionStack in PrintMembers
Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
RikkiGibson
2021-07-20T02:25:37Z
2021-07-21T18:04:34Z
4de5102100b3b6dc06ba21099c95ddf692022b32
dff569c162ab629ab598e2a458b3c1eabcd31b57
Call EnsureSufficientExecutionStack in PrintMembers. Related to dotnet/roslyn-analyzers#5068 Related to dotnet/csharplang#4951 Related to #48646
./src/Features/LanguageServer/Protocol/Handler/Diagnostics/AbstractPullDiagnosticHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="DiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<DiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, DiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, DiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, DiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, DiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, DiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); return result.ToArray(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Roslyn.Utilities; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler.Diagnostics { /// <summary> /// Root type for both document and workspace diagnostic pull requests. /// </summary> internal abstract class AbstractPullDiagnosticHandler<TDiagnosticsParams, TReport> : IRequestHandler<TDiagnosticsParams, TReport[]?> where TReport : DiagnosticReport { /// <summary> /// Special value we use to designate workspace diagnostics vs document diagnostics. Document diagnostics /// should always <see cref="DiagnosticReport.Supersedes"/> a workspace diagnostic as the former are 'live' /// while the latter are cached and may be stale. /// </summary> protected const int WorkspaceDiagnosticIdentifier = 1; protected const int DocumentDiagnosticIdentifier = 2; protected readonly IDiagnosticService DiagnosticService; /// <summary> /// Lock to protect <see cref="_documentIdToLastResultId"/> and <see cref="_nextDocumentResultId"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Mapping of a document to the last result id we reported for it. /// </summary> private readonly Dictionary<(Workspace workspace, DocumentId documentId), string> _documentIdToLastResultId = new(); /// <summary> /// The next available id to label results with. Note that results are tagged on a per-document bases. That /// way we can update diagnostics with the client with per-doc granularity. /// </summary> private long _nextDocumentResultId; public abstract string Method { get; } public bool MutatesSolutionState => false; public bool RequiresLSPSolution => true; protected AbstractPullDiagnosticHandler( IDiagnosticService diagnosticService) { DiagnosticService = diagnosticService; DiagnosticService.DiagnosticsUpdated += OnDiagnosticsUpdated; } public abstract TextDocumentIdentifier? GetTextDocumentIdentifier(TDiagnosticsParams diagnosticsParams); /// <summary> /// Gets the progress object to stream results to. /// </summary> protected abstract IProgress<TReport[]>? GetProgress(TDiagnosticsParams diagnosticsParams); /// <summary> /// Retrieve the previous results we reported. Used so we can avoid resending data for unchanged files. Also /// used so we can report which documents were removed and can have all their diagnostics cleared. /// </summary> protected abstract DiagnosticParams[]? GetPreviousResults(TDiagnosticsParams diagnosticsParams); /// <summary> /// Returns all the documents that should be processed in the desired order to process them in. /// </summary> protected abstract ImmutableArray<Document> GetOrderedDocuments(RequestContext context); /// <summary> /// Creates the <see cref="DiagnosticReport"/> instance we'll report back to clients to let them know our /// progress. Subclasses can fill in data specific to their needs as appropriate. /// </summary> protected abstract TReport CreateReport(TextDocumentIdentifier? identifier, VSDiagnostic[]? diagnostics, string? resultId); /// <summary> /// Produce the diagnostics for the specified document. /// </summary> protected abstract Task<ImmutableArray<DiagnosticData>> GetDiagnosticsAsync(RequestContext context, Document document, Option2<DiagnosticMode> diagnosticMode, CancellationToken cancellationToken); /// <summary> /// Generate the right diagnostic tags for a particular diagnostic. /// </summary> protected abstract DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData); private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs updateArgs) { if (updateArgs.DocumentId == null) return; // Ensure we do not clear the cached results while the handler is reading (and possibly then writing) // to the cached results. lock (_gate) { // Whenever we hear about changes to a document, drop the data we've stored for it. We'll recompute it as // necessary on the next request. _documentIdToLastResultId.Remove((updateArgs.Workspace, updateArgs.DocumentId)); } } public async Task<TReport[]?> HandleRequestAsync( TDiagnosticsParams diagnosticsParams, RequestContext context, CancellationToken cancellationToken) { context.TraceInformation($"{this.GetType()} started getting diagnostics"); // The progress object we will stream reports to. using var progress = BufferedProgress.Create(GetProgress(diagnosticsParams)); // Get the set of results the request said were previously reported. We can use this to determine both // what to skip, and what files we have to tell the client have been removed. var previousResults = GetPreviousResults(diagnosticsParams) ?? Array.Empty<DiagnosticParams>(); context.TraceInformation($"previousResults.Length={previousResults.Length}"); // First, let the client know if any workspace documents have gone away. That way it can remove those for // the user from squiggles or error-list. HandleRemovedDocuments(context, previousResults, progress); // Create a mapping from documents to the previous results the client says it has for them. That way as we // process documents we know if we should tell the client it should stay the same, or we can tell it what // the updated diagnostics are. var documentToPreviousDiagnosticParams = GetDocumentToPreviousDiagnosticParams(context, previousResults); // Next process each file in priority order. Determine if diagnostics are changed or unchanged since the // last time we notified the client. Report back either to the client so they can update accordingly. var orderedDocuments = GetOrderedDocuments(context); context.TraceInformation($"Processing {orderedDocuments.Length} documents"); foreach (var document in orderedDocuments) { context.TraceInformation($"Processing: {document.FilePath}"); if (!IncludeDocument(document, context.ClientName)) { context.TraceInformation($"Ignoring document '{document.FilePath}' because of razor/client-name mismatch"); continue; } if (HaveDiagnosticsChanged(documentToPreviousDiagnosticParams, document, out var newResultId)) { context.TraceInformation($"Diagnostics were changed for document: {document.FilePath}"); progress.Report(await ComputeAndReportCurrentDiagnosticsAsync(context, document, newResultId, cancellationToken).ConfigureAwait(false)); } else { context.TraceInformation($"Diagnostics were unchanged for document: {document.FilePath}"); // Nothing changed between the last request and this one. Report a (null-diagnostics, // same-result-id) response to the client as that means they should just preserve the current // diagnostics they have for this file. var previousParams = documentToPreviousDiagnosticParams[document]; progress.Report(CreateReport(previousParams.TextDocument, diagnostics: null, previousParams.PreviousResultId)); } } // If we had a progress object, then we will have been reporting to that. Otherwise, take what we've been // collecting and return that. context.TraceInformation($"{this.GetType()} finished getting diagnostics"); return progress.GetValues(); } private static bool IncludeDocument(Document document, string? clientName) { // Documents either belong to Razor or not. We can determine this by checking if the doc has a span-mapping // service or not. If we're not in razor, we do not include razor docs. If we are in razor, we only // include razor docs. var isRazorDoc = document.IsRazorDocument(); var wantsRazorDoc = clientName != null; return wantsRazorDoc == isRazorDoc; } private static Dictionary<Document, DiagnosticParams> GetDocumentToPreviousDiagnosticParams( RequestContext context, DiagnosticParams[] previousResults) { Contract.ThrowIfNull(context.Solution); var result = new Dictionary<Document, DiagnosticParams>(); foreach (var diagnosticParams in previousResults) { if (diagnosticParams.TextDocument != null) { var document = context.Solution.GetDocument(diagnosticParams.TextDocument); if (document != null) result[document] = diagnosticParams; } } return result; } private async Task<TReport> ComputeAndReportCurrentDiagnosticsAsync( RequestContext context, Document document, string resultId, CancellationToken cancellationToken) { // Being asked about this document for the first time. Or being asked again and we have different // diagnostics. Compute and report the current diagnostics info for this document. // Razor has a separate option for determining if they should be in push or pull mode. var diagnosticMode = document.IsRazorDocument() ? InternalDiagnosticsOptions.RazorDiagnosticMode : InternalDiagnosticsOptions.NormalDiagnosticMode; var workspace = document.Project.Solution.Workspace; var isPull = workspace.IsPullDiagnostics(diagnosticMode); context.TraceInformation($"Getting '{(isPull ? "pull" : "push")}' diagnostics with mode '{diagnosticMode}'"); using var _ = ArrayBuilder<VSDiagnostic>.GetInstance(out var result); if (isPull) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await GetDiagnosticsAsync(context, document, diagnosticMode, cancellationToken).ConfigureAwait(false); context.TraceInformation($"Got {diagnostics.Length} diagnostics"); foreach (var diagnostic in diagnostics) result.Add(ConvertDiagnostic(document, text, diagnostic)); } return CreateReport(ProtocolConversions.DocumentToTextDocumentIdentifier(document), result.ToArray(), resultId); } private void HandleRemovedDocuments(RequestContext context, DiagnosticParams[] previousResults, BufferedProgress<TReport> progress) { Contract.ThrowIfNull(context.Solution); foreach (var previousResult in previousResults) { var textDocument = previousResult.TextDocument; if (textDocument != null) { var document = context.Solution.GetDocument(textDocument); if (document == null) { context.TraceInformation($"Clearing diagnostics for removed document: {textDocument.Uri}"); // Client is asking server about a document that no longer exists (i.e. was removed/deleted from // the workspace). Report a (null-diagnostics, null-result-id) response to the client as that // means they should just consider the file deleted and should remove all diagnostics // information they've cached for it. progress.Report(CreateReport(textDocument, diagnostics: null, resultId: null)); } } } } /// <summary> /// Returns true if diagnostics have changed since the last request and if so, /// calculates a new resultId to use for subsequent computation and caches it. /// </summary> /// <param name="documentToPreviousDiagnosticParams">the resultIds the client sent us.</param> /// <param name="document">the document we are currently calculating results for.</param> /// <param name="newResultId">the resultId to report new diagnostics with if changed.</param> private bool HaveDiagnosticsChanged( Dictionary<Document, DiagnosticParams> documentToPreviousDiagnosticParams, Document document, [NotNullWhen(true)] out string? newResultId) { // Read and write the cached resultId to _documentIdToLastResultId in a single transaction // to prevent in-between updates to _documentIdToLastResultId triggered by OnDiagnosticsUpdated. lock (_gate) { var workspace = document.Project.Solution.Workspace; if (documentToPreviousDiagnosticParams.TryGetValue(document, out var previousParams) && _documentIdToLastResultId.TryGetValue((workspace, document.Id), out var lastReportedResultId) && lastReportedResultId == previousParams.PreviousResultId) { // Our cached resultId for the document matches the resultId the client passed to us. // This means the diagnostics have not changed and we do not need to re-compute. newResultId = null; return false; } // Keep track of the diagnostics we reported here so that we can short-circuit producing diagnostics for // the same diagnostic set in the future. Use a custom result-id per type (doc diagnostics or workspace // diagnostics) so that clients of one don't errantly call into the other. For example, a client // getting document diagnostics should not ask for workspace diagnostics with the result-ids it got for // doc-diagnostics. The two systems are different and cannot share results, or do things like report // what changed between each other. // // Note that we can safely update the map before computation as any cancellation or exception // during computation means that the client will never recieve this resultId and so cannot ask us for it. newResultId = $"{GetType().Name}:{_nextDocumentResultId++}"; _documentIdToLastResultId[(document.Project.Solution.Workspace, document.Id)] = newResultId; return true; } } private VSDiagnostic ConvertDiagnostic(Document document, SourceText text, DiagnosticData diagnosticData) { Contract.ThrowIfNull(diagnosticData.Message, $"Got a document diagnostic that did not have a {nameof(diagnosticData.Message)}"); Contract.ThrowIfNull(diagnosticData.DataLocation, $"Got a document diagnostic that did not have a {nameof(diagnosticData.DataLocation)}"); var project = document.Project; // We currently do not map diagnostics spans as // 1. Razor handles span mapping for razor files on their side. // 2. LSP does not allow us to report document pull diagnostics for a different file path. // 3. The VS LSP client does not support document pull diagnostics for files outside our content type. // 4. This matches classic behavior where we only squiggle the original location anyway. var useMappedSpan = false; return new VSDiagnostic { Source = GetType().Name, Code = diagnosticData.Id, Message = diagnosticData.Message, Severity = ConvertDiagnosticSeverity(diagnosticData.Severity), Range = ProtocolConversions.LinePositionToRange(DiagnosticData.GetLinePositionSpan(diagnosticData.DataLocation, text, useMappedSpan)), Tags = ConvertTags(diagnosticData), DiagnosticType = diagnosticData.Category, Projects = new[] { new ProjectAndContext { ProjectIdentifier = project.Id.Id.ToString(), ProjectName = project.Name, }, }, }; } private static LSP.DiagnosticSeverity ConvertDiagnosticSeverity(DiagnosticSeverity severity) => severity switch { // Hidden is translated in ConvertTags to pass along appropriate _ms tags // that will hide the item in a client that knows about those tags. DiagnosticSeverity.Hidden => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Info => LSP.DiagnosticSeverity.Hint, DiagnosticSeverity.Warning => LSP.DiagnosticSeverity.Warning, DiagnosticSeverity.Error => LSP.DiagnosticSeverity.Error, _ => throw ExceptionUtilities.UnexpectedValue(severity), }; /// <summary> /// If you make change in this method, please also update the corresponding file in /// src\VisualStudio\Xaml\Impl\Implementation\LanguageServer\Handler\Diagnostics\AbstractPullDiagnosticHandler.cs /// </summary> protected static DiagnosticTag[] ConvertTags(DiagnosticData diagnosticData, bool potentialDuplicate) { using var _ = ArrayBuilder<DiagnosticTag>.GetInstance(out var result); if (diagnosticData.Severity == DiagnosticSeverity.Hidden) { result.Add(VSDiagnosticTags.HiddenInEditor); result.Add(VSDiagnosticTags.HiddenInErrorList); result.Add(VSDiagnosticTags.SuppressEditorToolTip); } else { result.Add(VSDiagnosticTags.VisibleInErrorList); } if (potentialDuplicate) result.Add(VSDiagnosticTags.PotentialDuplicate); result.Add(diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Build) ? VSDiagnosticTags.BuildError : VSDiagnosticTags.IntellisenseError); if (diagnosticData.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) result.Add(DiagnosticTag.Unnecessary); return result.ToArray(); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharp/LineSeparators/CSharpLineSeparatorService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LineSeparator { [ExportLanguageService(typeof(ILineSeparatorService), LanguageNames.CSharp), Shared] internal class CSharpLineSeparatorService : ILineSeparatorService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLineSeparatorService() { } /// <summary> /// Given a tree returns line separator spans. /// The operation may take fairly long time on a big tree so it is cancellable. /// </summary> public async Task<IEnumerable<TextSpan>> GetLineSeparatorsAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var node = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var spans = new List<TextSpan>(); var blocks = node.Traverse<SyntaxNode>(textSpan, IsSeparableContainer); foreach (var block in blocks) { if (cancellationToken.IsCancellationRequested) { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } switch (block) { case TypeDeclarationSyntax typeBlock: ProcessNodeList(typeBlock.Members, spans, cancellationToken); continue; case NamespaceDeclarationSyntax namespaceBlock: ProcessUsings(namespaceBlock.Usings, spans, cancellationToken); ProcessNodeList(namespaceBlock.Members, spans, cancellationToken); continue; case CompilationUnitSyntax progBlock: ProcessUsings(progBlock.Usings, spans, cancellationToken); ProcessNodeList(progBlock.Members, spans, cancellationToken); break; } } return spans; } /// <summary>Node types that are interesting for line separation.</summary> private static bool IsSeparableBlock(SyntaxNode node) { if (SyntaxFacts.IsTypeDeclaration(node.Kind())) { return true; } switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return true; default: return false; } } /// <summary>Node types that may contain separable blocks.</summary> private static bool IsSeparableContainer(SyntaxNode node) { return node is TypeDeclarationSyntax || node is NamespaceDeclarationSyntax || node is CompilationUnitSyntax; } private static bool IsBadType(SyntaxNode node) { if (node is TypeDeclarationSyntax typeDecl) { if (typeDecl.OpenBraceToken.IsMissing || typeDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadEnum(SyntaxNode node) { if (node is EnumDeclarationSyntax enumDecl) { if (enumDecl.OpenBraceToken.IsMissing || enumDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadMethod(SyntaxNode node) { if (node is MethodDeclarationSyntax methodDecl) { if (methodDecl.Body != null && (methodDecl.Body.OpenBraceToken.IsMissing || methodDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadProperty(SyntaxNode node) => IsBadAccessorList(node as PropertyDeclarationSyntax); private static bool IsBadEvent(SyntaxNode node) => IsBadAccessorList(node as EventDeclarationSyntax); private static bool IsBadIndexer(SyntaxNode node) => IsBadAccessorList(node as IndexerDeclarationSyntax); private static bool IsBadAccessorList(BasePropertyDeclarationSyntax baseProperty) { if (baseProperty?.AccessorList == null) { return false; } return baseProperty.AccessorList.OpenBraceToken.IsMissing || baseProperty.AccessorList.CloseBraceToken.IsMissing; } private static bool IsBadConstructor(SyntaxNode node) { if (node is ConstructorDeclarationSyntax constructorDecl) { if (constructorDecl.Body != null && (constructorDecl.Body.OpenBraceToken.IsMissing || constructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadDestructor(SyntaxNode node) { if (node is DestructorDeclarationSyntax destructorDecl) { if (destructorDecl.Body != null && (destructorDecl.Body.OpenBraceToken.IsMissing || destructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadOperator(SyntaxNode node) { if (node is OperatorDeclarationSyntax operatorDecl) { if (operatorDecl.Body != null && (operatorDecl.Body.OpenBraceToken.IsMissing || operatorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadConversionOperator(SyntaxNode node) { if (node is ConversionOperatorDeclarationSyntax conversionDecl) { if (conversionDecl.Body != null && (conversionDecl.Body.OpenBraceToken.IsMissing || conversionDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadNode(SyntaxNode node) { if (node is IncompleteMemberSyntax) { return true; } if (IsBadType(node) || IsBadEnum(node) || IsBadMethod(node) || IsBadProperty(node) || IsBadEvent(node) || IsBadIndexer(node) || IsBadConstructor(node) || IsBadDestructor(node) || IsBadOperator(node) || IsBadConversionOperator(node)) { return true; } return false; } private static void ProcessUsings(SyntaxList<UsingDirectiveSyntax> usings, List<TextSpan> spans, CancellationToken cancellationToken) { Contract.ThrowIfNull(spans); if (usings.Any()) { AddLineSeparatorSpanForNode(usings.Last(), spans, cancellationToken); } } /// <summary> /// If node is separable and not the last in its container => add line separator after the node /// If node is separable and not the first in its container => ensure separator before the node /// last separable node in Program needs separator after it. /// </summary> private static void ProcessNodeList<T>(SyntaxList<T> children, List<TextSpan> spans, CancellationToken cancellationToken) where T : SyntaxNode { Contract.ThrowIfNull(spans); if (children.Count == 0) { // nothing to separate return; } // first child needs no separator var seenSeparator = true; for (var i = 0; i < children.Count - 1; i++) { cancellationToken.ThrowIfCancellationRequested(); var cur = children[i]; if (!IsSeparableBlock(cur)) { seenSeparator = false; } else { if (!seenSeparator) { var prev = children[i - 1]; AddLineSeparatorSpanForNode(prev, spans, cancellationToken); } AddLineSeparatorSpanForNode(cur, spans, cancellationToken); seenSeparator = true; } } // last child may need separator only before it var lastChild = children.Last(); if (IsSeparableBlock(lastChild)) { if (!seenSeparator) { var nextToLast = children[children.Count - 2]; AddLineSeparatorSpanForNode(nextToLast, spans, cancellationToken); } if (lastChild.IsParentKind(SyntaxKind.CompilationUnit)) { AddLineSeparatorSpanForNode(lastChild, spans, cancellationToken); } } } private static void AddLineSeparatorSpanForNode(SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { if (IsBadNode(node)) { return; } var span = GetLineSeparatorSpanForNode(node); if (IsLegalSpanForLineSeparator(node.SyntaxTree, span, cancellationToken)) { spans.Add(span); } } private static bool IsLegalSpanForLineSeparator(SyntaxTree syntaxTree, TextSpan textSpan, CancellationToken cancellationToken) { // A span is a legal location for a line separator if the following line // contains only whitespace or the span is the last line in the buffer. var line = syntaxTree.GetText(cancellationToken).Lines.IndexOf(textSpan.End); if (line == syntaxTree.GetText(cancellationToken).Lines.Count - 1) { return true; } if (string.IsNullOrWhiteSpace(syntaxTree.GetText(cancellationToken).Lines[line + 1].ToString())) { return true; } return false; } private static TextSpan GetLineSeparatorSpanForNode(SyntaxNode node) { // we only want to underline the node with a long line // for this purpose the last token is as good as the whole node, but has // simpler and typically single line geometry (so it will be easier to find "bottom") return node.GetLastToken().Span; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LineSeparator { [ExportLanguageService(typeof(ILineSeparatorService), LanguageNames.CSharp), Shared] internal class CSharpLineSeparatorService : ILineSeparatorService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLineSeparatorService() { } /// <summary> /// Given a tree returns line separator spans. /// The operation may take fairly long time on a big tree so it is cancellable. /// </summary> public async Task<IEnumerable<TextSpan>> GetLineSeparatorsAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var node = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var spans = new List<TextSpan>(); var blocks = node.Traverse<SyntaxNode>(textSpan, IsSeparableContainer); foreach (var block in blocks) { if (cancellationToken.IsCancellationRequested) return SpecializedCollections.EmptyEnumerable<TextSpan>(); switch (block) { case TypeDeclarationSyntax typeBlock: ProcessNodeList(typeBlock.Members, spans, cancellationToken); continue; case BaseNamespaceDeclarationSyntax namespaceBlock: ProcessUsings(namespaceBlock.Usings, spans, cancellationToken); ProcessNodeList(namespaceBlock.Members, spans, cancellationToken); continue; case CompilationUnitSyntax progBlock: ProcessUsings(progBlock.Usings, spans, cancellationToken); ProcessNodeList(progBlock.Members, spans, cancellationToken); break; } } return spans; } /// <summary>Node types that are interesting for line separation.</summary> private static bool IsSeparableBlock(SyntaxNode node) { if (SyntaxFacts.IsTypeDeclaration(node.Kind())) { return true; } switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return true; default: return false; } } /// <summary>Node types that may contain separable blocks.</summary> private static bool IsSeparableContainer(SyntaxNode node) => node is TypeDeclarationSyntax or BaseNamespaceDeclarationSyntax or CompilationUnitSyntax; private static bool IsBadType(SyntaxNode node) { if (node is TypeDeclarationSyntax typeDecl) { if (typeDecl.OpenBraceToken.IsMissing || typeDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadEnum(SyntaxNode node) { if (node is EnumDeclarationSyntax enumDecl) { if (enumDecl.OpenBraceToken.IsMissing || enumDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadMethod(SyntaxNode node) { if (node is MethodDeclarationSyntax methodDecl) { if (methodDecl.Body != null && (methodDecl.Body.OpenBraceToken.IsMissing || methodDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadProperty(SyntaxNode node) => IsBadAccessorList(node as PropertyDeclarationSyntax); private static bool IsBadEvent(SyntaxNode node) => IsBadAccessorList(node as EventDeclarationSyntax); private static bool IsBadIndexer(SyntaxNode node) => IsBadAccessorList(node as IndexerDeclarationSyntax); private static bool IsBadAccessorList(BasePropertyDeclarationSyntax? baseProperty) { if (baseProperty?.AccessorList == null) return false; return baseProperty.AccessorList.OpenBraceToken.IsMissing || baseProperty.AccessorList.CloseBraceToken.IsMissing; } private static bool IsBadConstructor(SyntaxNode node) { if (node is ConstructorDeclarationSyntax constructorDecl) { if (constructorDecl.Body != null && (constructorDecl.Body.OpenBraceToken.IsMissing || constructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadDestructor(SyntaxNode node) { if (node is DestructorDeclarationSyntax destructorDecl) { if (destructorDecl.Body != null && (destructorDecl.Body.OpenBraceToken.IsMissing || destructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadOperator(SyntaxNode node) { if (node is OperatorDeclarationSyntax operatorDecl) { if (operatorDecl.Body != null && (operatorDecl.Body.OpenBraceToken.IsMissing || operatorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadConversionOperator(SyntaxNode node) { if (node is ConversionOperatorDeclarationSyntax conversionDecl) { if (conversionDecl.Body != null && (conversionDecl.Body.OpenBraceToken.IsMissing || conversionDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadNode(SyntaxNode node) { if (node is IncompleteMemberSyntax) { return true; } if (IsBadType(node) || IsBadEnum(node) || IsBadMethod(node) || IsBadProperty(node) || IsBadEvent(node) || IsBadIndexer(node) || IsBadConstructor(node) || IsBadDestructor(node) || IsBadOperator(node) || IsBadConversionOperator(node)) { return true; } return false; } private static void ProcessUsings(SyntaxList<UsingDirectiveSyntax> usings, List<TextSpan> spans, CancellationToken cancellationToken) { Contract.ThrowIfNull(spans); if (usings.Any()) { AddLineSeparatorSpanForNode(usings.Last(), spans, cancellationToken); } } /// <summary> /// If node is separable and not the last in its container => add line separator after the node /// If node is separable and not the first in its container => ensure separator before the node /// last separable node in Program needs separator after it. /// </summary> private static void ProcessNodeList<T>(SyntaxList<T> children, List<TextSpan> spans, CancellationToken cancellationToken) where T : SyntaxNode { Contract.ThrowIfNull(spans); if (children.Count == 0) { // nothing to separate return; } // first child needs no separator var seenSeparator = true; for (var i = 0; i < children.Count - 1; i++) { cancellationToken.ThrowIfCancellationRequested(); var cur = children[i]; if (!IsSeparableBlock(cur)) { seenSeparator = false; } else { if (!seenSeparator) { var prev = children[i - 1]; AddLineSeparatorSpanForNode(prev, spans, cancellationToken); } AddLineSeparatorSpanForNode(cur, spans, cancellationToken); seenSeparator = true; } } // last child may need separator only before it var lastChild = children.Last(); if (IsSeparableBlock(lastChild)) { if (!seenSeparator) { var nextToLast = children[children.Count - 2]; AddLineSeparatorSpanForNode(nextToLast, spans, cancellationToken); } if (lastChild.IsParentKind(SyntaxKind.CompilationUnit)) { AddLineSeparatorSpanForNode(lastChild, spans, cancellationToken); } } } private static void AddLineSeparatorSpanForNode(SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { if (IsBadNode(node)) { return; } var span = GetLineSeparatorSpanForNode(node); if (IsLegalSpanForLineSeparator(node.SyntaxTree, span, cancellationToken)) { spans.Add(span); } } private static bool IsLegalSpanForLineSeparator(SyntaxTree syntaxTree, TextSpan textSpan, CancellationToken cancellationToken) { // A span is a legal location for a line separator if the following line // contains only whitespace or the span is the last line in the buffer. var line = syntaxTree.GetText(cancellationToken).Lines.IndexOf(textSpan.End); if (line == syntaxTree.GetText(cancellationToken).Lines.Count - 1) { return true; } if (string.IsNullOrWhiteSpace(syntaxTree.GetText(cancellationToken).Lines[line + 1].ToString())) { return true; } return false; } private static TextSpan GetLineSeparatorSpanForNode(SyntaxNode node) { // we only want to underline the node with a long line // for this purpose the last token is as good as the whole node, but has // simpler and typically single line geometry (so it will be easier to find "bottom") return node.GetLastToken().Span; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SuggestionModeCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class SuggestionModeCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(CSharpSuggestionModeCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstExplicitArgument() { // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (int x, i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstImplicitArgument() { // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (x, i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstImplicitArgumentInMethodCall() { var markup = @"class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar((x, i $$ } } "; // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstExplicitArgumentInMethodCall() { var markup = @"class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar((int x, i $$ } } "; // Could be a deconstruction expression await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateTypeExpected1() { var markup = @"using System; class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar($$ } } "; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateTypeExpected2() => await VerifyBuilderAsync(AddUsingDirectives("using System;", AddInsideMethod(@"Func<int, int, int> f = $$"))); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectInitializerDelegateType() { var markup = @"using System; using System.Collections.Generic; using System.Linq; class Program { public Func<int> myfunc { get; set; } } class a { void goo() { var b = new Program() { myfunc = $$ } }"; await VerifyBuilderAsync(markup); } [Fact, WorkItem(817145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/817145"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExplicitArrayInitializer() { var markup = @"using System; class a { void goo() { Func<int, int>[] myfunc = new Func<int, int>[] { $$; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerUnknownType() { var markup = @"using System; class a { void goo() { var a = new [] { $$; } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerKnownDelegateType() { var markup = @"using System; class a { void goo() { var a = new [] { x => 2 * x, $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorUnknownType() { var markup = @"using System; class a { void goo() { var a = true ? $$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorKnownDelegateType1() { var markup = @"using System; class a { void goo() { var a = true ? x => x * 2 : $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorKnownDelegateType2() { var markup = @"using System; class a { void goo() { Func<int, int> a = true ? $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverloadTakesADelegate1() { var markup = @"using System; class a { void goo(int a) { } void goo(Func<int, int> a) { } void bar() { this.goo($$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverloadTakesDelegate2() { var markup = @"using System; class a { void goo(int i, int a) { } void goo(int i, Func<int, int> a) { } void bar() { this.goo(1, $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExplicitCastToDelegate() { var markup = @"using System; class a { void bar() { (Func<int, int>) ($$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(860580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860580")] public async Task ReturnStatement() { var markup = @"using System; class a { Func<int, int> bar() { return $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType1() { var markup = @"using System; class a { int bar() { var q = new {$$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType2() { var markup = @"using System; class a { int bar() { var q = new {$$ 1, 2 }; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType3() { var markup = @"using System; class a { int bar() { var q = new {Name = 1, $$ }; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInFromClause() { var markup = @"using System; using System.Linq; class a { int bar() { var q = from $$ } }"; await VerifyBuilderAsync(markup.ToString()); } [WorkItem(823968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/823968")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInJoinClause() { var markup = @"using System; using System.Linq; using System.Collections.Generic; class a { int bar() { var list = new List<int>(); var q = from a in list join $$ } }"; await VerifyBuilderAsync(markup.ToString()); } [WorkItem(544290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544290")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$, e) => { }); } }"; await VerifyBuilderAsync(markup); } [WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteNestedParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(((a$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpressionInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInObjectCreation() { var markup = @"using System; class Program { static void Main() { Program x = new P$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInArrayCreation() { var markup = @"using System; class Program { static void Main() { Program[] x = new $$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInArrayCreation2() { var markup = @"using System; class Program { static void Main() { Program[] x = new Pr$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a$$, b) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionInVarDeclaration2() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteLambdaInActionDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a$$, b) } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInActionDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a$$, b: b) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInActionDeclaration2() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a: a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a: a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderForLinqExpression() { var markup = @"using System; using System.Linq.Expressions; public class Class { public void Goo(Expression<Action<int>> arg) { Goo($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInTypeParameter() { var markup = @"using System; using System.Linq.Expressions; public class Class { public void Goo(Expression<Action<int>> arg) { Enumerable.Empty<$$ } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(611477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611477")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodFaultTolerance() { var markup = @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Outer { public struct ImmutableArray<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } public static class ReadOnlyArrayExtensions { public static ImmutableArray<TResult> Select<T, TResult>(this ImmutableArray<T> array, Func<T, TResult> selector) { throw new NotImplementedException(); } } namespace Inner { class Program { static void Main(string[] args) { args.Select($$ } } } } "; await VerifyBuilderAsync(markup); } [WorkItem(834609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaWithAutomaticBraceCompletion() { var markup = @"using System; using System; public class Class { public void Goo() { EventHandler h = (s$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThisConstructorInitializer() { var markup = @"using System; class X { X(Func<X> x) : this($$) { } }"; await VerifyBuilderAsync(markup); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseConstructorInitializer() { var markup = @"using System; class B { public B(Func<B> x) {} } class D : B { D() : base($$) { } }"; await VerifyBuilderAsync(markup); } [WorkItem(887842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887842")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PreprocessorExpression() { var markup = @"class C { #if $$ }"; await VerifyBuilderAsync(markup); } [WorkItem(967254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/967254")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerAfterNew() { var markup = @"using System; class a { void goo() { int[] a = new $$; } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceDeclaration_Unqualified() { var markup = @"namespace $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceDeclaration_Qualified() { var markup = @"namespace A.$$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FileScopedNamespaceDeclaration_Unqualified() { var markup = @"namespace $$;"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FileScopedNamespaceDeclaration_Qualified() { var markup = @"namespace A.$$;"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialClassName() { var markup = @"partial class $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialStructName() { var markup = @"partial struct $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialInterfaceName() { var markup = @"partial interface $$"; await VerifyBuilderAsync(markup); } [WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnwrapParamsArray() { var markup = @" using System; class C { C(params Action<int>[] a) { new C($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotUnwrapRegularArray() { var markup = @" using System; class C { C(Action<int>[] a) { new C($$ } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(47662, "https://github.com/dotnet/roslyn/issues/47662")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaExpressionInImplicitObjectCreation() { var markup = @" using System; class C { C(Action<int> a) { C c = new($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderWhenDelegateInferredRightOfDotInInvocation() { var markup = @" class C { Action a = Task.$$ }"; await VerifyNotBuilderAsync(markup); } [WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderInTypeArgument() { var markup = @" namespace ConsoleApplication1 { class Program { class N { } static void Main(string[] args) { Program.N n = Load<Program.$$ } static T Load<T>() => default(T); } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(16176, "https://github.com/dotnet/roslyn/issues/16176")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderForLambdaAfterNew() { var markup = @" class C { Action a = new $$ }"; await VerifyNotBuilderAsync(markup); } [WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncLambda() { var markup = @" using System; using System.Threading.Tasks; class Program { public void B(Func<int, int, Task<int>> f) { } void A() { B(async($$"; await VerifyBuilderAsync(markup); } [WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncLambdaAfterComma() { var markup = @" using System; using System.Threading.Tasks; class Program { public void B(Func<int, int, Task<int>> f) { } void A() { B(async(p1, $$"; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod1() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod2() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod3() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod4() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod5() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$)) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod6() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar((a, $$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod7() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(async (a$$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithNonDelegateExtensionAndInstanceMethod1() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, int val) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$ } } "; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInDeclarationPattern() { var markup = @" class C { void M() { var e = new object(); if (e is int o$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInDeclarationPattern2() { var markup = @" class C { void M() { var e = new object(); if (e is System.Collections.Generic.List<int> an$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInRecursivePattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is { P: 1 } o$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInPropertyPattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is { P: int o$$ }) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInAndPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 and int a$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInAndOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is (int or 1) and int a$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInSwitchStatement() { var markup = @" class C { void M() { var e = new object(); switch (e) { case int o$$ } } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInSwitchExpression() { var markup = @" class C { void M() { var e = new object(); var result = e switch { int o$$ } } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Declaration() { var markup = @" class C { void M() { var e = new object(); if (e is not int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Declaration2() { var markup = @" class C { void M() { var e = new object(); if (e is not (1 and int o$$)) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Recursive() { var markup = @" class C { int P { get; } void M(C test) { if (test is not { P: 1 } o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 or int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInAndOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 or int and int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInRecursiveOrPattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is null or { P: 1 } o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar) { var markup = $@" using System; interface Foo {{ bool Bar() => true; }} class P {{ void M(Foo f) {{ f.Bar({(hasTypedChar ? "s" : "")}$$ }} }}"; await VerifyNotBuilderAsync(markup); } [WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLambda, bool hasTypedChar) { var overload = isLambda ? "bool Bar(Func<int, bool> predicate) => true;" : "bool Bar(int x) => true;"; var markup = $@" using System; interface Foo {{ bool Bar() => true; {overload} }} class P {{ void M(Foo f) {{ f.Bar({(hasTypedChar ? "s" : "")}$$ }} }}"; if (isLambda) { await VerifyBuilderAsync(markup); } else { await VerifyNotBuilderAsync(markup); } } [InlineData("params string[] x")] [InlineData("string x = null, string y = null")] [InlineData("string x = null, string y = null, params string[] z")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(49656, "https://github.com/dotnet/roslyn/issues/49656")] public async Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList) { var markup = $@" using System; interface Foo {{ bool Bar({overloadParameterList}) => true; bool Bar(Func<int, bool> predicate) => true; }} class P {{ void M(Foo f) {{ f.Bar($$) }} }}"; await VerifyBuilderAsync(markup); } private async Task VerifyNotBuilderAsync(string markup) => await VerifyWorkerAsync(markup, isBuilder: false); private async Task VerifyBuilderAsync(string markup) => await VerifyWorkerAsync(markup, isBuilder: true); private async Task VerifyWorkerAsync(string markup, bool isBuilder) { MarkupTestFile.GetPosition(markup, out var code, out int position); using (var workspaceFixture = new CSharpTestWorkspaceFixture()) { workspaceFixture.GetWorkspace(ExportProvider); var document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular); await CheckResultsAsync(document1, position, isBuilder); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate: false); await CheckResultsAsync(document2, position, isBuilder); } } } private async Task CheckResultsAsync(Document document, int position, bool isBuilder) { var triggerInfos = new List<CompletionTrigger>(); triggerInfos.Add(CompletionTrigger.CreateInsertionTrigger('a')); triggerInfos.Add(CompletionTrigger.Invoke); triggerInfos.Add(CompletionTrigger.CreateDeletionTrigger('z')); var service = GetCompletionService(document.Project); var provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet<string>.Empty)); foreach (var triggerInfo in triggerInfos) { var completionList = await service.GetTestAccessor().GetContextAsync( provider, document, position, triggerInfo, options: null, cancellationToken: CancellationToken.None); if (isBuilder) { Assert.NotNull(completionList); Assert.True(completionList.SuggestionModeItem != null, "Expecting a suggestion mode, but none was present"); } else { if (completionList != null) { Assert.True(completionList.SuggestionModeItem == null, "group.Builder == " + (completionList.SuggestionModeItem != null ? completionList.SuggestionModeItem.DisplayText : "null")); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class SuggestionModeCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(CSharpSuggestionModeCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstExplicitArgument() { // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (int x, i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstImplicitArgument() { // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(AddInsideMethod(@"Func<int, int, int> f = (x, i $$")); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstImplicitArgumentInMethodCall() { var markup = @"class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar((x, i $$ } } "; // The right-hand-side parses like a possible deconstruction or tuple type await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterFirstExplicitArgumentInMethodCall() { var markup = @"class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar((int x, i $$ } } "; // Could be a deconstruction expression await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateTypeExpected1() { var markup = @"using System; class c { private void bar(Func<int, int, bool> f) { } private void goo() { bar($$ } } "; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateTypeExpected2() => await VerifyBuilderAsync(AddUsingDirectives("using System;", AddInsideMethod(@"Func<int, int, int> f = $$"))); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectInitializerDelegateType() { var markup = @"using System; using System.Collections.Generic; using System.Linq; class Program { public Func<int> myfunc { get; set; } } class a { void goo() { var b = new Program() { myfunc = $$ } }"; await VerifyBuilderAsync(markup); } [Fact, WorkItem(817145, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/817145"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExplicitArrayInitializer() { var markup = @"using System; class a { void goo() { Func<int, int>[] myfunc = new Func<int, int>[] { $$; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerUnknownType() { var markup = @"using System; class a { void goo() { var a = new [] { $$; } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerKnownDelegateType() { var markup = @"using System; class a { void goo() { var a = new [] { x => 2 * x, $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorUnknownType() { var markup = @"using System; class a { void goo() { var a = true ? $$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorKnownDelegateType1() { var markup = @"using System; class a { void goo() { var a = true ? x => x * 2 : $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TernaryOperatorKnownDelegateType2() { var markup = @"using System; class a { void goo() { Func<int, int> a = true ? $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverloadTakesADelegate1() { var markup = @"using System; class a { void goo(int a) { } void goo(Func<int, int> a) { } void bar() { this.goo($$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverloadTakesDelegate2() { var markup = @"using System; class a { void goo(int i, int a) { } void goo(int i, Func<int, int> a) { } void bar() { this.goo(1, $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExplicitCastToDelegate() { var markup = @"using System; class a { void bar() { (Func<int, int>) ($$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(860580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860580")] public async Task ReturnStatement() { var markup = @"using System; class a { Func<int, int> bar() { return $$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType1() { var markup = @"using System; class a { int bar() { var q = new {$$ } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType2() { var markup = @"using System; class a { int bar() { var q = new {$$ 1, 2 }; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInAnonymousType3() { var markup = @"using System; class a { int bar() { var q = new {Name = 1, $$ }; } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInFromClause() { var markup = @"using System; using System.Linq; class a { int bar() { var q = from $$ } }"; await VerifyBuilderAsync(markup.ToString()); } [WorkItem(823968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/823968")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderInJoinClause() { var markup = @"using System; using System.Linq; using System.Collections.Generic; class a { int bar() { var list = new List<int>(); var q = from a in list join $$ } }"; await VerifyBuilderAsync(markup.ToString()); } [WorkItem(544290, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544290")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$, e) => { }); } }"; await VerifyBuilderAsync(markup); } [WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler((a$$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(544379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544379")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteNestedParenthesizedLambdaArgument() { var markup = @"using System; class Program { static void Main(string[] args) { Console.CancelKeyPress += new ConsoleCancelEventHandler(((a$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpressionInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInObjectCreation() { var markup = @"using System; class Program { static void Main() { Program x = new P$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInArrayCreation() { var markup = @"using System; class Program { static void Main() { Program[] x = new $$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24432, "https://github.com/dotnet/roslyn/issues/24432")] public async Task TestInArrayCreation2() { var markup = @"using System; class Program { static void Main() { Program[] x = new Pr$$ } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a$$, b) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleExpressionInVarDeclaration2() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteLambdaInActionDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a$$, b) } }"; await VerifyBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInActionDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a$$, b: b) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInActionDeclaration2() { var markup = @"using System; class Program { static void Main(string[] args) { System.Action x = (a: a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleWithNamesInVarDeclaration() { var markup = @"using System; class Program { static void Main(string[] args) { var x = (a: a, b$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BuilderForLinqExpression() { var markup = @"using System; using System.Linq.Expressions; public class Class { public void Goo(Expression<Action<int>> arg) { Goo($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(546363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546363")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInTypeParameter() { var markup = @"using System; using System.Linq.Expressions; public class Class { public void Goo(Expression<Action<int>> arg) { Enumerable.Empty<$$ } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(611477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/611477")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodFaultTolerance() { var markup = @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Outer { public struct ImmutableArray<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } public static class ReadOnlyArrayExtensions { public static ImmutableArray<TResult> Select<T, TResult>(this ImmutableArray<T> array, Func<T, TResult> selector) { throw new NotImplementedException(); } } namespace Inner { class Program { static void Main(string[] args) { args.Select($$ } } } } "; await VerifyBuilderAsync(markup); } [WorkItem(834609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaWithAutomaticBraceCompletion() { var markup = @"using System; using System; public class Class { public void Goo() { EventHandler h = (s$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThisConstructorInitializer() { var markup = @"using System; class X { X(Func<X> x) : this($$) { } }"; await VerifyBuilderAsync(markup); } [WorkItem(858112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858112")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseConstructorInitializer() { var markup = @"using System; class B { public B(Func<B> x) {} } class D : B { D() : base($$) { } }"; await VerifyBuilderAsync(markup); } [WorkItem(887842, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/887842")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PreprocessorExpression() { var markup = @"class C { #if $$ }"; await VerifyBuilderAsync(markup); } [WorkItem(967254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/967254")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ImplicitArrayInitializerAfterNew() { var markup = @"using System; class a { void goo() { int[] a = new $$; } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceDeclaration_Unqualified() { var markup = @"namespace $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceDeclaration_Qualified() { var markup = @"namespace A.$$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FileScopedNamespaceDeclaration_Unqualified() { var markup = @"namespace $$;"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FileScopedNamespaceDeclaration_Qualified() { var markup = @"namespace A.$$;"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialClassName() { var markup = @"partial class $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialStructName() { var markup = @"partial struct $$"; await VerifyBuilderAsync(markup); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialInterfaceName() { var markup = @"partial interface $$"; await VerifyBuilderAsync(markup); } [WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnwrapParamsArray() { var markup = @" using System; class C { C(params Action<int>[] a) { new C($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(12818, "https://github.com/dotnet/roslyn/issues/12818")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotUnwrapRegularArray() { var markup = @" using System; class C { C(Action<int>[] a) { new C($$ } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(47662, "https://github.com/dotnet/roslyn/issues/47662")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaExpressionInImplicitObjectCreation() { var markup = @" using System; class C { C(Action<int> a) { C c = new($$ } }"; await VerifyBuilderAsync(markup); } [WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderWhenDelegateInferredRightOfDotInInvocation() { var markup = @" class C { Action a = Task.$$ }"; await VerifyNotBuilderAsync(markup); } [WorkItem(15443, "https://github.com/dotnet/roslyn/issues/15443")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderInTypeArgument() { var markup = @" namespace ConsoleApplication1 { class Program { class N { } static void Main(string[] args) { Program.N n = Load<Program.$$ } static T Load<T>() => default(T); } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(16176, "https://github.com/dotnet/roslyn/issues/16176")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotBuilderForLambdaAfterNew() { var markup = @" class C { Action a = new $$ }"; await VerifyNotBuilderAsync(markup); } [WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncLambda() { var markup = @" using System; using System.Threading.Tasks; class Program { public void B(Func<int, int, Task<int>> f) { } void A() { B(async($$"; await VerifyBuilderAsync(markup); } [WorkItem(20937, "https://github.com/dotnet/roslyn/issues/20937")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AsyncLambdaAfterComma() { var markup = @" using System; using System.Threading.Tasks; class Program { public void B(Func<int, int, Task<int>> f) { } void A() { B(async(p1, $$"; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod1() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod2() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod3() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod4() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod5() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(($$)) } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod6() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar((a, $$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithExtensionAndInstanceMethod7() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, Action<int> action) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(async (a$$ } } "; await VerifyBuilderAsync(markup); } [WorkItem(28586, "https://github.com/dotnet/roslyn/issues/28586")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithNonDelegateExtensionAndInstanceMethod1() { var markup = @" using System; public sealed class Goo { public void Bar() { } } public static class GooExtensions { public static void Bar(this Goo goo, int val) { } } public static class Repro { public static void ReproMethod(Goo goo) { goo.Bar(a$$ } } "; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInDeclarationPattern() { var markup = @" class C { void M() { var e = new object(); if (e is int o$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInDeclarationPattern2() { var markup = @" class C { void M() { var e = new object(); if (e is System.Collections.Generic.List<int> an$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInRecursivePattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is { P: 1 } o$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInPropertyPattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is { P: int o$$ }) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInAndPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 and int a$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInAndOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is (int or 1) and int a$$) } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInSwitchStatement() { var markup = @" class C { void M() { var e = new object(); switch (e) { case int o$$ } } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInSwitchExpression() { var markup = @" class C { void M() { var e = new object(); var result = e switch { int o$$ } } }"; await VerifyBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Declaration() { var markup = @" class C { void M() { var e = new object(); if (e is not int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Declaration2() { var markup = @" class C { void M() { var e = new object(); if (e is not (1 and int o$$)) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInNotPattern_Recursive() { var markup = @" class C { int P { get; } void M(C test) { if (test is not { P: 1 } o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 or int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInAndOrPattern() { var markup = @" class C { void M() { var e = new object(); if (e is 1 or int and int o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestMissingInRecursiveOrPattern() { var markup = @" class C { int P { get; } void M(C test) { if (test is null or { P: 1 } o$$) } }"; await VerifyNotBuilderAsync(markup); } [WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstArgumentOfInvocation_NoParameter(bool hasTypedChar) { var markup = $@" using System; interface Foo {{ bool Bar() => true; }} class P {{ void M(Foo f) {{ f.Bar({(hasTypedChar ? "s" : "")}$$ }} }}"; await VerifyNotBuilderAsync(markup); } [WorkItem(46927, "https://github.com/dotnet/roslyn/issues/46927")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstArgumentOfInvocation_PossibleLambdaExpression(bool isLambda, bool hasTypedChar) { var overload = isLambda ? "bool Bar(Func<int, bool> predicate) => true;" : "bool Bar(int x) => true;"; var markup = $@" using System; interface Foo {{ bool Bar() => true; {overload} }} class P {{ void M(Foo f) {{ f.Bar({(hasTypedChar ? "s" : "")}$$ }} }}"; if (isLambda) { await VerifyBuilderAsync(markup); } else { await VerifyNotBuilderAsync(markup); } } [InlineData("params string[] x")] [InlineData("string x = null, string y = null")] [InlineData("string x = null, string y = null, params string[] z")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(49656, "https://github.com/dotnet/roslyn/issues/49656")] public async Task FirstArgumentOfInvocation_WithOverloadAcceptEmptyArgumentList(string overloadParameterList) { var markup = $@" using System; interface Foo {{ bool Bar({overloadParameterList}) => true; bool Bar(Func<int, bool> predicate) => true; }} class P {{ void M(Foo f) {{ f.Bar($$) }} }}"; await VerifyBuilderAsync(markup); } private async Task VerifyNotBuilderAsync(string markup) => await VerifyWorkerAsync(markup, isBuilder: false); private async Task VerifyBuilderAsync(string markup) => await VerifyWorkerAsync(markup, isBuilder: true); private async Task VerifyWorkerAsync(string markup, bool isBuilder) { MarkupTestFile.GetPosition(markup, out var code, out int position); using (var workspaceFixture = new CSharpTestWorkspaceFixture()) { workspaceFixture.GetWorkspace(ExportProvider); var document1 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular); await CheckResultsAsync(document1, position, isBuilder); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = workspaceFixture.UpdateDocument(code, SourceCodeKind.Regular, cleanBeforeUpdate: false); await CheckResultsAsync(document2, position, isBuilder); } } } private async Task CheckResultsAsync(Document document, int position, bool isBuilder) { var triggerInfos = new List<CompletionTrigger>(); triggerInfos.Add(CompletionTrigger.CreateInsertionTrigger('a')); triggerInfos.Add(CompletionTrigger.Invoke); triggerInfos.Add(CompletionTrigger.CreateDeletionTrigger('z')); var service = GetCompletionService(document.Project); var provider = Assert.Single(service.GetTestAccessor().GetAllProviders(ImmutableHashSet<string>.Empty)); foreach (var triggerInfo in triggerInfos) { var completionList = await service.GetTestAccessor().GetContextAsync( provider, document, position, triggerInfo, options: null, cancellationToken: CancellationToken.None); if (isBuilder) { Assert.NotNull(completionList); Assert.True(completionList.SuggestionModeItem != null, "Expecting a suggestion mode, but none was present"); } else { if (completionList != null) { Assert.True(completionList.SuggestionModeItem == null, "group.Builder == " + (completionList.SuggestionModeItem != null ? completionList.SuggestionModeItem.DisplayText : "null")); } } } } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/ConvertAnonymousTypeToClass/ConvertAnonymousTypeToClassTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass { public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest { private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_FileScopedNamespace() { var text = @" namespace N; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_Explicit() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { int hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(); } } internal class NewClass { public NewClass() { } public override bool Equals(object obj) { return obj is NewClass other; } public override int GetHashCode() { return 0; } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(); } } internal record NewRecord(); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1); } } internal class NewClass { public int A { get; } public NewClass(int a) { A = a; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A; } public override int GetHashCode() { return -862436692 + A.GetHashCode(); } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1); } } internal record NewRecord(int A); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, b); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewRecord|}(1, b); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); var t2 = new NewRecord(3, 4); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnlyConvertMatchingTypesInSameMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixAllMatchesInSingleMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixNotAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia2() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NotIfReferencesAnonymousTypeInternally() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleNestedInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object))); } } internal class NewClass { public int A { get; } public object B { get; } public NewClass(int a, object b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && EqualityComparer<object>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task RenameAnnotationOnStartingPoint() { var text = @" class Test { void Method() { var t1 = new { a = 1, b = 2 }; var t2 = [||]new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new NewClass(1, 2); var t2 = new {|Rename:NewClass|}(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task UpdateReferences() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Console.WriteLine(t1.a + t1?.b); } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Console.WriteLine(t1.A + t1?.B); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewClass|}<X, Y>(x, y); } } internal class NewClass<X, Y> where X : struct where Y : class, new() { public List<X> A { get; } public Y[] B { get; } public NewClass(List<X> a, Y[] b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass<X, Y> other && System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) && System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters_CSharp9() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewRecord|}<X, Y>(x, y); } } internal record NewRecord<X, Y>(List<X> A, Y[] B) where X : struct where Y : class, new(); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NewTypeNameCollision() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } class NewClass { } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass1|}(1, 2); } } class NewClass { } internal class NewClass1 { public int A { get; } public int B { get; } public NewClass1(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass1 other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int Item { get; } public NewClass(int a, int item) { A = a; Item = item; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && Item == other.Item; } public override int GetHashCode() { var hashCode = -335756622; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + Item.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int Item); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestNewSelection() { var text = @" class Test { void Method() { var t1 = [|new|] { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Action a = () => { var t2 = new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Action a = () => { var t2 = new NewClass(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; Action a = () => { var t2 = [||]new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); Action a = () => { var t2 = new {|Rename:NewClass|}(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; void Goo() { var t2 = new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); void Goo() { var t2 = new NewClass(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; void Goo() { var t2 = [||]new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); void Goo() { var t2 = new {|Rename:NewClass|}(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection1() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 }|]; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection2() { var text = @" class Test { void Method() { [|var t1 = new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection3() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingComma() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2, }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingCommaButPreservingTrivia() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 // and // more , }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 // and // more ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertAnonymousTypeToClass { public class ConvertAnonymousTypeToClassTests : AbstractCSharpCodeActionTest { private static readonly ParseOptions CSharp8 = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8); protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertAnonymousTypeToClassCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_FileScopedNamespace() { var text = @" namespace N; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousType_Explicit() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { int hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(); } } internal class NewClass { public NewClass() { } public override bool Equals(object obj) { return obj is NewClass other; } public override int GetHashCode() { return 0; } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnEmptyAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(); } } internal record NewRecord(); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1); } } internal class NewClass { public int A { get; } public NewClass(int a) { A = a; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A; } public override int GetHashCode() { return -862436692 + A.GetHashCode(); } }", parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnSingleFieldAnonymousType_CSharp9() { await TestInRegularAndScriptAsync(@" class Test { void Method() { var t1 = [||]new { a = 1 }; } } ", @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1); } } internal record NewRecord(int A); "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, b); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeWithInferredName_CSharp9() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewRecord|}(1, b); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesInSameMethod_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); var t2 = new NewRecord(3, 4); } } internal record NewRecord(int A, int B); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleInstancesAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task OnlyConvertMatchingTypesInSameMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixAllMatchesInSingleMethod() { var text = @" class Test { void Method(int b) { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b }; var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } "; var expected = @" class Test { void Method(int b) { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, b); var t3 = new { a = 4 }; var t4 = new { b = 5, a = 6 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestFixNotAcrossMethods() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); var t2 = new NewClass(3, 4); } void Method2() { var t1 = new { a = 1, b = 2 }; var t2 = new { a = 3, b = 4 }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestTrivia2() { var text = @" class Test { void Method() { var t1 = /*1*/ [||]new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; var t2 = /*1*/ new /*2*/ { /*3*/ a /*4*/ = /*5*/ 1 /*7*/ , /*8*/ b /*9*/ = /*10*/ 2 /*11*/ } /*12*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new {|Rename:NewClass|}( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; var t2 = /*1*/ new NewClass( /*3*/ 1 /*7*/ , /*8*/ 2 /*11*/ ) /*12*/ ; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NotIfReferencesAnonymousTypeInternally() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = new { c = 1, d = 2 } }; } } "; await TestMissingInRegularAndScriptAsync(text); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertMultipleNestedInstancesInSameMethod() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = (object)new { a = 1, b = default(object) } }; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, (object)new NewClass(1, default(object))); } } internal class NewClass { public int A { get; } public object B { get; } public NewClass(int a, object b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && EqualityComparer<object>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task RenameAnnotationOnStartingPoint() { var text = @" class Test { void Method() { var t1 = new { a = 1, b = 2 }; var t2 = [||]new { a = 3, b = 4 }; } } "; var expected = @" class Test { void Method() { var t1 = new NewClass(1, 2); var t2 = new {|Rename:NewClass|}(3, 4); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task UpdateReferences() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Console.WriteLine(t1.a + t1?.b); } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Console.WriteLine(t1.A + t1?.B); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewClass|}<X, Y>(x, y); } } internal class NewClass<X, Y> where X : struct where Y : class, new() { public List<X> A { get; } public Y[] B { get; } public NewClass(List<X> a, Y[] b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass<X, Y> other && System.Collections.Generic.EqualityComparer<List<X>>.Default.Equals(A, other.A) && System.Collections.Generic.EqualityComparer<Y[]>.Default.Equals(B, other.B); } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<List<X>>.Default.GetHashCode(A); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<Y[]>.Default.GetHashCode(B); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task CapturedTypeParameters_CSharp9() { var text = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = [||]new { a = x, b = y }; } } "; var expected = @" class Test<X> where X : struct { void Method<Y>(List<X> x, Y[] y) where Y : class, new() { var t1 = new {|Rename:NewRecord|}<X, Y>(x, y); } } internal record NewRecord<X, Y>(List<X> A, Y[] B) where X : struct where Y : class, new(); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task NewTypeNameCollision() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; } } class NewClass { } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass1|}(1, 2); } } class NewClass { } internal class NewClass1 { public int A { get; } public int B { get; } public NewClass1(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass1 other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int Item { get; } public NewClass(int a, int item) { A = a; Item = item; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && Item == other.Item; } public override int GetHashCode() { var hashCode = -335756622; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + Item.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestDuplicatedName_CSharp9() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, a = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewRecord|}(1, 2); } } internal record NewRecord(int A, int Item); "; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestNewSelection() { var text = @" class Test { void Method() { var t1 = [|new|] { a = 1, b = 2 }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; Action a = () => { var t2 = new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); Action a = () => { var t2 = new NewClass(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLambda2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; Action a = () => { var t2 = [||]new { a = 3, b = 4 }; }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); Action a = () => { var t2 = new {|Rename:NewClass|}(3, 4); }; } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction1() { var text = @" using System; class Test { void Method() { var t1 = [||]new { a = 1, b = 2 }; void Goo() { var t2 = new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); void Goo() { var t2 = new NewClass(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task TestInLocalFunction2() { var text = @" using System; class Test { void Method() { var t1 = new { a = 1, b = 2 }; void Goo() { var t2 = [||]new { a = 3, b = 4 }; } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewClass(1, 2); void Goo() { var t2 = new {|Rename:NewClass|}(3, 4); } } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection1() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 }|]; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection2() { var text = @" class Test { void Method() { [|var t1 = new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertSingleAnonymousTypeSelection3() { var text = @" class Test { void Method() { var t1 = [|new { a = 1, b = 2 };|] } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}(1, 2); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingComma() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2, }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } [WorkItem(45747, "https://github.com/dotnet/roslyn/issues/45747")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertAnonymousTypeToClass)] public async Task ConvertOmittingTrailingCommaButPreservingTrivia() { var text = @" class Test { void Method() { var t1 = [||]new { a = 1, b = 2 // and // more , }; } } "; var expected = @" class Test { void Method() { var t1 = new {|Rename:NewClass|}( 1, 2 // and // more ); } } internal class NewClass { public int A { get; } public int B { get; } public NewClass(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewClass other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } }"; await TestInRegularAndScriptAsync(text, expected, options: this.PreferImplicitTypeWithInfo(), parseOptions: CSharp8); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/ConvertTupleToStruct/ConvertTupleToStructTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTupleToStruct { using VerifyCS = CSharpCodeRefactoringVerifier<CSharpConvertTupleToStructCodeRefactoringProvider>; [UseExportProvider] public class ConvertTupleToStructTests { private static OptionsCollection PreferImplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion }, }; private static async Task TestAsync( string text, string expected, int index = 0, string? equivalenceKey = null, LanguageVersion languageVersion = LanguageVersion.CSharp9, OptionsCollection? options = null, TestHost testHost = TestHost.InProcess, string[]? actions = null) { if (index != 0) Assert.NotNull(equivalenceKey); options ??= new OptionsCollection(LanguageNames.CSharp); await new VerifyCS.Test { TestCode = text, FixedCode = expected, TestHost = testHost, LanguageVersion = languageVersion, CodeActionIndex = index, CodeActionEquivalenceKey = equivalenceKey, ExactActionSetOffered = actions, Options = { options }, }.RunAsync(); } #region update containing member tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct(int a, int b) { public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host) { var text = @" namespace N; class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct(int a, int b) { public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord_MismatchedNameCasing(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct { public int A; public int B; public NewStruct(int a, int b) { A = a; B = b; } public void Deconstruct(out int a, out int b) { a = A; b = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int A; public int B; public NewStruct(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewStruct other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = A; b = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_ChangeArgumentNameCase_Uppercase(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(p_a_: 1, p_b_: 2); } } internal struct NewStruct { public int A; public int B; public NewStruct(int p_a_, int p_b_) { A = p_a_; B = p_b_; } public override bool Equals(object obj) { return obj is NewStruct other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } public void Deconstruct(out int p_a_, out int p_b_) { p_a_ = A; p_b_ = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; var symbolSpecification = new SymbolSpecification( null, "Name2", ImmutableArray.Create(new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)), accessibilityList: default, modifiers: default); var namingStyle = new NamingStyle( Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase, name: "Name2", prefix: "p_", suffix: "_", wordSeparator: ""); var namingRule = new SerializableNamingRule() { SymbolSpecificationID = symbolSpecification.ID, NamingStyleID = namingStyle.ID, EnforcementLevel = ReportDiagnostic.Error }; var info = new NamingStylePreferences( ImmutableArray.Create(symbolSpecification), ImmutableArray.Create(namingStyle), ImmutableArray.Create(namingRule)); var options = PreferImplicitTypeWithInfo(); options.Add(NamingStyleOptions.NamingPreferences, info); await TestAsync(text, expected, options: options, testHost: host); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_Explicit(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { int hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeNoNames(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int, int)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int, int) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypePartialNames(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, b: 2); } } internal struct NewStruct { public int Item1; public int b; public NewStruct(int item1, int b) { Item1 = item1; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && b == other.b; } public override int GetHashCode() { var hashCode = 174326978; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int b) { item1 = Item1; b = this.b; } public static implicit operator (int, int b)(NewStruct value) { return (value.Item1, value.b); } public static implicit operator NewStruct((int, int b) value) { return new NewStruct(value.Item1, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType(TestHost host) { var text = @" class Test { void Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int a, int b) t2 = (a: 1, b: 2); } } "; var expected = @" class Test { void Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType2(TestHost host) { var text = @" class Test { (int a, int b) Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int a, int b) t2 = (a: 1, b: 2); return default; } } "; var expected = @" class Test { NewStruct Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); return default; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType3(TestHost host) { var text = @" class Test { (int a, int b) Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int b, int a) t2 = (b: 1, a: 2); return default; } } "; var expected = @" class Test { NewStruct Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); (int b, int a) t2 = (b: 1, a: 2); return default; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType4(TestHost host) { var text = @" class Test { void Method() { (int a, int b) t1 = (a: 1, b: 2); [||](int a, int b) t2 = (a: 1, b: 2); } } "; var expected = @" class Test { void Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeInNamespace(TestHost host) { var text = @" namespace N { class Test { void Method() { var t1 = [||](a: 1, b: 2); } } } "; var expected = @" namespace N { class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } } } "; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestNonLiteralNames_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test { void Method() { var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}()); } } internal struct NewStruct { public object a; public object b; public NewStruct(object a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && EqualityComparer<object>.Default.Equals(a, other.a) && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out object a, out object b) { a = this.a; b = this.b; } public static implicit operator (object a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((object a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestNonLiteralNames_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}()); } } internal struct NewStruct { public object a; public object b; public NewStruct(object a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && System.Collections.Generic.EqualityComparer<object>.Default.Equals(a, other.a) && System.Collections.Generic.EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out object a, out object b) { a = this.a; b = this.b; } public static implicit operator (object a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((object a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeWithInferredName(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleInstancesInSameMethod(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleInstancesAcrossMethods(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task OnlyConvertMatchingTypesInSameMethod(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestFixAllMatchesInSingleMethod(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestFixNotAcrossMethods(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestTrivia_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test { void Method() { var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } internal struct NewStruct { public int a; public object Item2; public NewStruct(int a, object item2) { this.a = a; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(Item2, other.Item2); } public override int GetHashCode() { var hashCode = 913311208; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Item2); return hashCode; } public void Deconstruct(out int a, out object item2) { a = this.a; item2 = Item2; } public static implicit operator (int a, object)(NewStruct value) { return (value.a, value.Item2); } public static implicit operator NewStruct((int a, object) value) { return new NewStruct(value.a, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestTrivia_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } internal struct NewStruct { public int a; public object Item2; public NewStruct(int a, object item2) { this.a = a; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && System.Collections.Generic.EqualityComparer<object>.Default.Equals(Item2, other.Item2); } public override int GetHashCode() { var hashCode = 913311208; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(Item2); return hashCode; } public void Deconstruct(out int a, out object item2) { a = this.a; item2 = Item2; } public static implicit operator (int a, object)(NewStruct value) { return (value.a, value.Item2); } public static implicit operator NewStruct((int a, object) value) { return new NewStruct(value.a, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task NotIfReferencesAnonymousTypeInternally(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: new { c = 1, d = 2 }); } } "; await TestAsync(text, text, testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task RenameAnnotationOnStartingPoint(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: 2); var t2 = [||](a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task CapturedMethodTypeParameters_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = [||](a: x, b: y); } } "; var expected = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = new NewStruct<X, Y>(x, y); } } internal struct NewStruct<X, Y> where X : struct where Y : class, new() { public List<X> a; public Y[] b; public NewStruct(List<X> a, Y[] b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<X, Y> other && EqualityComparer<List<X>>.Default.Equals(a, other.a) && EqualityComparer<Y[]>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out List<X> a, out Y[] b) { a = this.a; b = this.b; } public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value) { return (value.a, value.b); } public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value) { return new NewStruct<X, Y>(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task CapturedMethodTypeParameters_WithoutUsings(TestHost host) { var text = @" class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = [||](a: x, b: y); } } "; var expected = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = new NewStruct<X, Y>(x, y); } } internal struct NewStruct<X, Y> where X : struct where Y : class, new() { public List<X> a; public Y[] b; public NewStruct(List<X> a, Y[] b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<X, Y> other && EqualityComparer<List<X>>.Default.Equals(a, other.a) && EqualityComparer<Y[]>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out List<X> a, out Y[] b) { a = this.a; b = this.b; } public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value) { return (value.a, value.b); } public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value) { return new NewStruct<X, Y>(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task NewTypeNameCollision(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } class NewStruct { } "; var expected = @" class Test { void Method() { var t1 = new NewStruct1(a: 1, b: 2); } } class NewStruct { } internal struct NewStruct1 { public int a; public int b; public NewStruct1(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct1 other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct1 value) { return (value.a, value.b); } public static implicit operator NewStruct1((int a, int b) value) { return new NewStruct1(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestDuplicatedName(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, a: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, a: 2); } } internal struct NewStruct { public int a; public int a; public NewStruct(int a, int a) { this.a = a; this.a = a; } public override bool Equals(object obj) { return obj is NewStruct other && this.a == other.a && this.a == other.a; } public override int GetHashCode() { var hashCode = 2068208952; hashCode = hashCode * -1521134295 + this.a.GetHashCode(); hashCode = hashCode * -1521134295 + this.a.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int a) { a = this.a; a = this.a; } public static implicit operator (int a, int a)(NewStruct value) { return (value.a, value.a); } public static implicit operator NewStruct((int a, int a) value) { return new NewStruct(value.a, value.a); } }"; await new VerifyCS.Test { TestCode = text, FixedCode = expected, TestHost = host, ExpectedDiagnostics = { // /0/Test0.cs(6,25): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(6, 25, 6, 26), }, FixedState = { ExpectedDiagnostics = { // /0/Test0.cs(6,22): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'NewStruct.NewStruct(int, int)' DiagnosticResult.CompilerError("CS7036").WithSpan(6, 22, 6, 31).WithArguments("a", "NewStruct.NewStruct(int, int)"), // /0/Test0.cs(13,16): error CS0102: The type 'NewStruct' already contains a definition for 'a' DiagnosticResult.CompilerError("CS0102").WithSpan(13, 16, 13, 17).WithArguments("NewStruct", "a"), // /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"), // /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"), // /0/Test0.cs(15,33): error CS0100: The parameter name 'a' is a duplicate DiagnosticResult.CompilerError("CS0100").WithSpan(15, 33, 15, 34).WithArguments("a"), // /0/Test0.cs(17,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(17, 14, 17, 15).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(17,18): error CS0229: Ambiguity between 'int' and 'int' DiagnosticResult.CompilerError("CS0229").WithSpan(17, 18, 17, 19).WithArguments("int", "int"), // /0/Test0.cs(18,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(18, 14, 18, 15).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(18,18): error CS0229: Ambiguity between 'int' and 'int' DiagnosticResult.CompilerError("CS0229").WithSpan(18, 18, 18, 19).WithArguments("int", "int"), // /0/Test0.cs(24,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(24, 21, 24, 22).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(24,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(24, 32, 24, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(25,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(25, 21, 25, 22).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(25,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(25, 32, 25, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(31,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(31, 50, 31, 51).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(32,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(32, 50, 32, 51).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"), // /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"), // /0/Test0.cs(36,48): error CS0100: The parameter name 'a' is a duplicate DiagnosticResult.CompilerError("CS0100").WithSpan(36, 48, 36, 49).WithArguments("a"), // /0/Test0.cs(38,9): error CS0229: Ambiguity between 'out int' and 'out int' DiagnosticResult.CompilerError("CS0229").WithSpan(38, 9, 38, 10).WithArguments("out int", "out int"), // /0/Test0.cs(38,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(38, 18, 38, 19).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(39,9): error CS0229: Ambiguity between 'out int' and 'out int' DiagnosticResult.CompilerError("CS0229").WithSpan(39, 9, 39, 10).WithArguments("out int", "out int"), // /0/Test0.cs(39,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(39, 18, 39, 19).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(42,49): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(42, 49, 42, 50), // /0/Test0.cs(44,23): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(44, 23, 44, 24).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(44,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(44, 32, 44, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(47,59): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(47, 59, 47, 60), // /0/Test0.cs(49,36): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a' DiagnosticResult.CompilerError("CS0229").WithSpan(49, 36, 49, 37).WithArguments("(int a, int a).a", "(int a, int a).a"), // /0/Test0.cs(49,45): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a' DiagnosticResult.CompilerError("CS0229").WithSpan(49, 45, 49, 46).WithArguments("(int a, int a).a", "(int a, int a).a"), } }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLambda1(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); Action a = () => { var t2 = (a: 3, b: 4); }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); Action a = () => { var t2 = new NewStruct(a: 3, b: 4); }; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLambda2(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = (a: 1, b: 2); Action a = () => { var t2 = [||](a: 3, b: 4); }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); Action a = () => { var t2 = new NewStruct(a: 3, b: 4); }; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLocalFunction1(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); void Goo() { var t2 = (a: 3, b: 4); } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLocalFunction2(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = (a: 1, b: 2); void Goo() { var t2 = [||](a: 3, b: 4); } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertWithDefaultNames1(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, 2); var t2 = (1, 2); var t3 = (a: 1, b: 2); var t4 = (Item1: 1, Item2: 2); var t5 = (Item1: 1, Item2: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); var t2 = new NewStruct(1, 2); var t3 = (a: 1, b: 2); var t4 = new NewStruct(item1: 1, item2: 2); var t5 = new NewStruct(item1: 1, item2: 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int, int)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int, int) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertWithDefaultNames2(TestHost host) { var text = @" class Test { void Method() { var t1 = (1, 2); var t2 = (1, 2); var t3 = (a: 1, b: 2); var t4 = [||](Item1: 1, Item2: 2); var t5 = (Item1: 1, Item2: 2); } }"; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); var t2 = new NewStruct(1, 2); var t3 = (a: 1, b: 2); var t4 = new NewStruct(item1: 1, item2: 2); var t5 = new NewStruct(item1: 1, item2: 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int Item1, int Item2)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int Item1, int Item2) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, }); } #endregion #region update containing type tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host) { var text = @" using System; class Test<T> { void Method(T t) { var t1 = [||](a: t, b: 2); } T t; void Goo() { var t2 = (a: t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } "; var expected = @" using System; using System.Collections.Generic; class Test<T> { void Method(T t) { var t1 = new NewStruct<T>(t, b: 2); } T t; void Goo() { var t2 = new NewStruct<T>(t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } internal struct NewStruct<T> { public T a; public int b; public NewStruct(T a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<T> other && EqualityComparer<T>.Default.Equals(a, other.a) && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out T a, out int b) { a = this.a; b = this.b; } public static implicit operator (T a, int b)(NewStruct<T> value) { return (value.a, value.b); } public static implicit operator NewStruct<T>((T a, int b) value) { return new NewStruct<T>(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host) { var text = @" class Test<T> { void Method(T t) { var t1 = [||](a: t, b: 2); } T t; void Goo() { var t2 = (a: t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } "; var expected = @" using System.Collections.Generic; class Test<T> { void Method(T t) { var t1 = new NewStruct<T>(t, b: 2); } T t; void Goo() { var t2 = new NewStruct<T>(t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } internal struct NewStruct<T> { public T a; public int b; public NewStruct(T a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<T> other && EqualityComparer<T>.Default.Equals(a, other.a) && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out T a, out int b) { a = this.a; b = this.b; } public static implicit operator (T a, int b)(NewStruct<T> value) { return (value.a, value.b); } public static implicit operator NewStruct<T>((T a, int b) value) { return new NewStruct<T>(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_SinglePart_SingleFile(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); } void Goo() { var t2 = (a: 3, b: 4); } } class Other { void Method() { var t1 = (a: 1, b: 2); } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_MultiplePart_SingleFile(TestHost host) { var text = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } class Other { void Method() { var t1 = (a: 1, b: 2); } } "; var expected = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Test { NewStruct Goo() { var t2 = new NewStruct(a: 3, b: 4); return default; } } class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_MultiplePart_MultipleFile(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Test { NewStruct Goo() { var t2 = new NewStruct(a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; await new VerifyCS.Test { TestState = { Sources = { text1, text2, } }, FixedState = { Sources = { expected1, expected2, } }, CodeActionIndex = 1, CodeActionEquivalenceKey = Scope.ContainingType.ToString(), TestHost = host, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion update containing project tests #region update containing project tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInProject_MultiplePart_MultipleFile_WithNamespace(TestHost host) { var text1 = @" using System; namespace N { partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } } }"; var text2 = @" using System; partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; namespace N { partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } } }"; var expected2 = @" using System; partial class Test { N.NewStruct Goo() { var t2 = new N.NewStruct(a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = new N.NewStruct(a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 2, CodeActionEquivalenceKey = Scope.ContainingProject.ToString(), TestHost = host, TestState = { Sources = { text1, text2, }, }, FixedState = { Sources = { expected1, expected2 }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion #region update dependent projects [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateDependentProjects_DirectDependency(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } public struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Other { void Goo() { var t1 = new NewStruct(a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 3, CodeActionEquivalenceKey = Scope.DependentProjects.ToString(), TestHost = host, TestState = { Sources = { text1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { text2 }, AdditionalProjectReferences = { "TestProject" }, } }, }, FixedState = { Sources = { expected1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { expected2 }, AdditionalProjectReferences = { "TestProject" }, } }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateDependentProjects_NoDependency(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } public struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 3, CodeActionEquivalenceKey = Scope.DependentProjects.ToString(), TestHost = host, TestState = { Sources = { text1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { text2 } } }, }, FixedState = { Sources = { expected1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { expected2 } } }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertTupleToStruct { using VerifyCS = CSharpCodeRefactoringVerifier<CSharpConvertTupleToStructCodeRefactoringProvider>; [UseExportProvider] public class ConvertTupleToStructTests { private static OptionsCollection PreferImplicitTypeWithInfo() => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.VarElsewhere, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, true, NotificationOption2.Suggestion }, { CSharpCodeStyleOptions.VarForBuiltInTypes, true, NotificationOption2.Suggestion }, }; private static async Task TestAsync( string text, string expected, int index = 0, string? equivalenceKey = null, LanguageVersion languageVersion = LanguageVersion.CSharp9, OptionsCollection? options = null, TestHost testHost = TestHost.InProcess, string[]? actions = null) { if (index != 0) Assert.NotNull(equivalenceKey); options ??= new OptionsCollection(LanguageNames.CSharp); await new VerifyCS.Test { TestCode = text, FixedCode = expected, TestHost = testHost, LanguageVersion = languageVersion, CodeActionIndex = index, CodeActionEquivalenceKey = equivalenceKey, ExactActionSetOffered = actions, Options = { options }, }.RunAsync(); } #region update containing member tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct(int a, int b) { public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord_FileScopedNamespace(TestHost host) { var text = @" namespace N; class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" namespace N; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct(int a, int b) { public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeToRecord_MismatchedNameCasing(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal record struct NewStruct { public int A; public int B; public NewStruct(int a, int b) { A = a; B = b; } public void Deconstruct(out int a, out int b) { a = A; b = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; await TestAsync(text, expected, languageVersion: LanguageVersion.Preview, options: PreferImplicitTypeWithInfo(), testHost: host); } [WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_ChangeArgumentNameCase(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int A; public int B; public NewStruct(int a, int b) { A = a; B = b; } public override bool Equals(object obj) { return obj is NewStruct other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = A; b = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [WorkItem(45451, "https://github.com/dotnet/roslyn/issues/45451")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_ChangeArgumentNameCase_Uppercase(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](A: 1, B: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(p_a_: 1, p_b_: 2); } } internal struct NewStruct { public int A; public int B; public NewStruct(int p_a_, int p_b_) { A = p_a_; B = p_b_; } public override bool Equals(object obj) { return obj is NewStruct other && A == other.A && B == other.B; } public override int GetHashCode() { var hashCode = -1817952719; hashCode = hashCode * -1521134295 + A.GetHashCode(); hashCode = hashCode * -1521134295 + B.GetHashCode(); return hashCode; } public void Deconstruct(out int p_a_, out int p_b_) { p_a_ = A; p_b_ = B; } public static implicit operator (int A, int B)(NewStruct value) { return (value.A, value.B); } public static implicit operator NewStruct((int A, int B) value) { return new NewStruct(value.A, value.B); } }"; var symbolSpecification = new SymbolSpecification( null, "Name2", ImmutableArray.Create(new SymbolSpecification.SymbolKindOrTypeKind(SymbolKind.Parameter)), accessibilityList: default, modifiers: default); var namingStyle = new NamingStyle( Guid.NewGuid(), capitalizationScheme: Capitalization.CamelCase, name: "Name2", prefix: "p_", suffix: "_", wordSeparator: ""); var namingRule = new SerializableNamingRule() { SymbolSpecificationID = symbolSpecification.ID, NamingStyleID = namingStyle.ID, EnforcementLevel = ReportDiagnostic.Error }; var info = new NamingStylePreferences( ImmutableArray.Create(symbolSpecification), ImmutableArray.Create(namingStyle), ImmutableArray.Create(namingRule)); var options = PreferImplicitTypeWithInfo(); options.Add(NamingStyleOptions.NamingPreferences, info); await TestAsync(text, expected, options: options, testHost: host); } [WorkItem(39916, "https://github.com/dotnet/roslyn/issues/39916")] [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleType_Explicit(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { int hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeNoNames(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int, int)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int, int) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypePartialNames(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, b: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, b: 2); } } internal struct NewStruct { public int Item1; public int b; public NewStruct(int item1, int b) { Item1 = item1; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && b == other.b; } public override int GetHashCode() { var hashCode = 174326978; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int b) { item1 = Item1; b = this.b; } public static implicit operator (int, int b)(NewStruct value) { return (value.Item1, value.b); } public static implicit operator NewStruct((int, int b) value) { return new NewStruct(value.Item1, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType(TestHost host) { var text = @" class Test { void Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int a, int b) t2 = (a: 1, b: 2); } } "; var expected = @" class Test { void Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType2(TestHost host) { var text = @" class Test { (int a, int b) Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int a, int b) t2 = (a: 1, b: 2); return default; } } "; var expected = @" class Test { NewStruct Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); return default; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType3(TestHost host) { var text = @" class Test { (int a, int b) Method() { [||](int a, int b) t1 = (a: 1, b: 2); (int b, int a) t2 = (b: 1, a: 2); return default; } } "; var expected = @" class Test { NewStruct Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); (int b, int a) t2 = (b: 1, a: 2); return default; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertFromType4(TestHost host) { var text = @" class Test { void Method() { (int a, int b) t1 = (a: 1, b: 2); [||](int a, int b) t2 = (a: 1, b: 2); } } "; var expected = @" class Test { void Method() { NewStruct t1 = new NewStruct(a: 1, b: 2); NewStruct t2 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeInNamespace(TestHost host) { var text = @" namespace N { class Test { void Method() { var t1 = [||](a: 1, b: 2); } } } "; var expected = @" namespace N { class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } } } "; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestNonLiteralNames_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test { void Method() { var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}()); } } internal struct NewStruct { public object a; public object b; public NewStruct(object a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && EqualityComparer<object>.Default.Equals(a, other.a) && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out object a, out object b) { a = this.a; b = this.b; } public static implicit operator (object a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((object a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestNonLiteralNames_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: {|CS0103:Goo|}(), b: {|CS0103:Bar|}()); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct({|CS0103:Goo|}(), {|CS0103:Bar|}()); } } internal struct NewStruct { public object a; public object b; public NewStruct(object a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && System.Collections.Generic.EqualityComparer<object>.Default.Equals(a, other.a) && System.Collections.Generic.EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out object a, out object b) { a = this.a; b = this.b; } public static implicit operator (object a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((object a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertSingleTupleTypeWithInferredName(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleInstancesInSameMethod(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleInstancesAcrossMethods(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task OnlyConvertMatchingTypesInSameMethod(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestFixAllMatchesInSingleMethod(TestHost host) { var text = @" class Test { void Method(int b) { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } "; var expected = @" class Test { void Method(int b) { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b); var t3 = (a: 4, b: 5, c: 6); var t4 = (b: 5, a: 6); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestFixNotAcrossMethods(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); var t2 = (a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } void Method2() { var t1 = (a: 1, b: 2); var t2 = (a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestTrivia_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test { void Method() { var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } internal struct NewStruct { public int a; public object Item2; public NewStruct(int a, object item2) { this.a = a; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(Item2, other.Item2); } public override int GetHashCode() { var hashCode = 913311208; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(Item2); return hashCode; } public void Deconstruct(out int a, out object item2) { a = this.a; item2 = Item2; } public static implicit operator (int a, object)(NewStruct value) { return (value.a, value.Item2); } public static implicit operator NewStruct((int a, object) value) { return new NewStruct(value.a, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestTrivia_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = /*1*/ [||]( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } "; var expected = @" class Test { void Method() { var t1 = /*1*/ new NewStruct( /*2*/ a /*3*/ : /*4*/ 1 /*5*/ , /*6*/ {|CS0103:b|} /*7*/ = /*8*/ 2 /*9*/ ) /*10*/ ; } } internal struct NewStruct { public int a; public object Item2; public NewStruct(int a, object item2) { this.a = a; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && System.Collections.Generic.EqualityComparer<object>.Default.Equals(Item2, other.Item2); } public override int GetHashCode() { var hashCode = 913311208; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + System.Collections.Generic.EqualityComparer<object>.Default.GetHashCode(Item2); return hashCode; } public void Deconstruct(out int a, out object item2) { a = this.a; item2 = Item2; } public static implicit operator (int a, object)(NewStruct value) { return (value.a, value.Item2); } public static implicit operator NewStruct((int a, object) value) { return new NewStruct(value.a, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task NotIfReferencesAnonymousTypeInternally(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: new { c = 1, d = 2 }); } } "; await TestAsync(text, text, testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod1_WithUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod1_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: (object)(a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod2_WithUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertMultipleNestedInstancesInSameMethod2_WithoutUsings(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: (object)[||](a: 1, b: default(object))); } } "; var expected = @" using System.Collections.Generic; class Test { void Method() { var t1 = new NewStruct(a: 1, (object)new NewStruct(a: 1, default(object))); } } internal struct NewStruct { public int a; public object b; public NewStruct(int a, object b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && EqualityComparer<object>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out int a, out object b) { a = this.a; b = this.b; } public static implicit operator (int a, object b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, object b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task RenameAnnotationOnStartingPoint(TestHost host) { var text = @" class Test { void Method() { var t1 = (a: 1, b: 2); var t2 = [||](a: 3, b: 4); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); var t2 = new NewStruct(a: 3, b: 4); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task CapturedMethodTypeParameters_WithUsings(TestHost host) { var text = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = [||](a: x, b: y); } } "; var expected = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = new NewStruct<X, Y>(x, y); } } internal struct NewStruct<X, Y> where X : struct where Y : class, new() { public List<X> a; public Y[] b; public NewStruct(List<X> a, Y[] b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<X, Y> other && EqualityComparer<List<X>>.Default.Equals(a, other.a) && EqualityComparer<Y[]>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out List<X> a, out Y[] b) { a = this.a; b = this.b; } public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value) { return (value.a, value.b); } public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value) { return new NewStruct<X, Y>(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task CapturedMethodTypeParameters_WithoutUsings(TestHost host) { var text = @" class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = [||](a: x, b: y); } } "; var expected = @" using System.Collections.Generic; class Test<X> where X : struct { void Method<Y>(System.Collections.Generic.List<X> x, Y[] y) where Y : class, new() { var t1 = new NewStruct<X, Y>(x, y); } } internal struct NewStruct<X, Y> where X : struct where Y : class, new() { public List<X> a; public Y[] b; public NewStruct(List<X> a, Y[] b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<X, Y> other && EqualityComparer<List<X>>.Default.Equals(a, other.a) && EqualityComparer<Y[]>.Default.Equals(b, other.b); } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<List<X>>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + EqualityComparer<Y[]>.Default.GetHashCode(b); return hashCode; } public void Deconstruct(out List<X> a, out Y[] b) { a = this.a; b = this.b; } public static implicit operator (List<X> a, Y[] b)(NewStruct<X, Y> value) { return (value.a, value.b); } public static implicit operator NewStruct<X, Y>((List<X> a, Y[] b) value) { return new NewStruct<X, Y>(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task NewTypeNameCollision(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, b: 2); } } class NewStruct { } "; var expected = @" class Test { void Method() { var t1 = new NewStruct1(a: 1, b: 2); } } class NewStruct { } internal struct NewStruct1 { public int a; public int b; public NewStruct1(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct1 other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct1 value) { return (value.a, value.b); } public static implicit operator NewStruct1((int a, int b) value) { return new NewStruct1(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestDuplicatedName(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](a: 1, a: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(a: 1, a: 2); } } internal struct NewStruct { public int a; public int a; public NewStruct(int a, int a) { this.a = a; this.a = a; } public override bool Equals(object obj) { return obj is NewStruct other && this.a == other.a && this.a == other.a; } public override int GetHashCode() { var hashCode = 2068208952; hashCode = hashCode * -1521134295 + this.a.GetHashCode(); hashCode = hashCode * -1521134295 + this.a.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int a) { a = this.a; a = this.a; } public static implicit operator (int a, int a)(NewStruct value) { return (value.a, value.a); } public static implicit operator NewStruct((int a, int a) value) { return new NewStruct(value.a, value.a); } }"; await new VerifyCS.Test { TestCode = text, FixedCode = expected, TestHost = host, ExpectedDiagnostics = { // /0/Test0.cs(6,25): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(6, 25, 6, 26), }, FixedState = { ExpectedDiagnostics = { // /0/Test0.cs(6,22): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'NewStruct.NewStruct(int, int)' DiagnosticResult.CompilerError("CS7036").WithSpan(6, 22, 6, 31).WithArguments("a", "NewStruct.NewStruct(int, int)"), // /0/Test0.cs(13,16): error CS0102: The type 'NewStruct' already contains a definition for 'a' DiagnosticResult.CompilerError("CS0102").WithSpan(13, 16, 13, 17).WithArguments("NewStruct", "a"), // /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"), // /0/Test0.cs(15,12): error CS0171: Field 'NewStruct.a' must be fully assigned before control is returned to the caller DiagnosticResult.CompilerError("CS0171").WithSpan(15, 12, 15, 21).WithArguments("NewStruct.a"), // /0/Test0.cs(15,33): error CS0100: The parameter name 'a' is a duplicate DiagnosticResult.CompilerError("CS0100").WithSpan(15, 33, 15, 34).WithArguments("a"), // /0/Test0.cs(17,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(17, 14, 17, 15).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(17,18): error CS0229: Ambiguity between 'int' and 'int' DiagnosticResult.CompilerError("CS0229").WithSpan(17, 18, 17, 19).WithArguments("int", "int"), // /0/Test0.cs(18,14): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(18, 14, 18, 15).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(18,18): error CS0229: Ambiguity between 'int' and 'int' DiagnosticResult.CompilerError("CS0229").WithSpan(18, 18, 18, 19).WithArguments("int", "int"), // /0/Test0.cs(24,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(24, 21, 24, 22).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(24,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(24, 32, 24, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(25,21): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(25, 21, 25, 22).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(25,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(25, 32, 25, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(31,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(31, 50, 31, 51).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(32,50): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(32, 50, 32, 51).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"), // /0/Test0.cs(36,17): error CS0177: The out parameter 'a' must be assigned to before control leaves the current method DiagnosticResult.CompilerError("CS0177").WithSpan(36, 17, 36, 28).WithArguments("a"), // /0/Test0.cs(36,48): error CS0100: The parameter name 'a' is a duplicate DiagnosticResult.CompilerError("CS0100").WithSpan(36, 48, 36, 49).WithArguments("a"), // /0/Test0.cs(38,9): error CS0229: Ambiguity between 'out int' and 'out int' DiagnosticResult.CompilerError("CS0229").WithSpan(38, 9, 38, 10).WithArguments("out int", "out int"), // /0/Test0.cs(38,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(38, 18, 38, 19).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(39,9): error CS0229: Ambiguity between 'out int' and 'out int' DiagnosticResult.CompilerError("CS0229").WithSpan(39, 9, 39, 10).WithArguments("out int", "out int"), // /0/Test0.cs(39,18): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(39, 18, 39, 19).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(42,49): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(42, 49, 42, 50), // /0/Test0.cs(44,23): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(44, 23, 44, 24).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(44,32): error CS0229: Ambiguity between 'NewStruct.a' and 'NewStruct.a' DiagnosticResult.CompilerError("CS0229").WithSpan(44, 32, 44, 33).WithArguments("NewStruct.a", "NewStruct.a"), // /0/Test0.cs(47,59): error CS8127: Tuple element names must be unique. DiagnosticResult.CompilerError("CS8127").WithSpan(47, 59, 47, 60), // /0/Test0.cs(49,36): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a' DiagnosticResult.CompilerError("CS0229").WithSpan(49, 36, 49, 37).WithArguments("(int a, int a).a", "(int a, int a).a"), // /0/Test0.cs(49,45): error CS0229: Ambiguity between '(int a, int a).a' and '(int a, int a).a' DiagnosticResult.CompilerError("CS0229").WithSpan(49, 45, 49, 46).WithArguments("(int a, int a).a", "(int a, int a).a"), } }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLambda1(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); Action a = () => { var t2 = (a: 3, b: 4); }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); Action a = () => { var t2 = new NewStruct(a: 3, b: 4); }; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLambda2(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = (a: 1, b: 2); Action a = () => { var t2 = [||](a: 3, b: 4); }; } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); Action a = () => { var t2 = new NewStruct(a: 3, b: 4); }; } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLocalFunction1(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); void Goo() { var t2 = (a: 3, b: 4); } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestInLocalFunction2(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = (a: 1, b: 2); void Goo() { var t2 = [||](a: 3, b: 4); } } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertWithDefaultNames1(TestHost host) { var text = @" class Test { void Method() { var t1 = [||](1, 2); var t2 = (1, 2); var t3 = (a: 1, b: 2); var t4 = (Item1: 1, Item2: 2); var t5 = (Item1: 1, Item2: 2); } } "; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); var t2 = new NewStruct(1, 2); var t3 = (a: 1, b: 2); var t4 = new NewStruct(item1: 1, item2: 2); var t5 = new NewStruct(item1: 1, item2: 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int, int)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int, int) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task ConvertWithDefaultNames2(TestHost host) { var text = @" class Test { void Method() { var t1 = (1, 2); var t2 = (1, 2); var t3 = (a: 1, b: 2); var t4 = [||](Item1: 1, Item2: 2); var t5 = (Item1: 1, Item2: 2); } }"; var expected = @" class Test { void Method() { var t1 = new NewStruct(1, 2); var t2 = new NewStruct(1, 2); var t3 = (a: 1, b: 2); var t4 = new NewStruct(item1: 1, item2: 2); var t5 = new NewStruct(item1: 1, item2: 2); } } internal struct NewStruct { public int Item1; public int Item2; public NewStruct(int item1, int item2) { Item1 = item1; Item2 = item2; } public override bool Equals(object obj) { return obj is NewStruct other && Item1 == other.Item1 && Item2 == other.Item2; } public override int GetHashCode() { var hashCode = -1030903623; hashCode = hashCode * -1521134295 + Item1.GetHashCode(); hashCode = hashCode * -1521134295 + Item2.GetHashCode(); return hashCode; } public void Deconstruct(out int item1, out int item2) { item1 = Item1; item2 = Item2; } public static implicit operator (int Item1, int Item2)(NewStruct value) { return (value.Item1, value.Item2); } public static implicit operator NewStruct((int Item1, int Item2) value) { return new NewStruct(value.Item1, value.Item2); } }"; await TestAsync(text, expected, options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type, }); } #endregion #region update containing type tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestCapturedTypeParameter_UpdateType_WithUsings(TestHost host) { var text = @" using System; class Test<T> { void Method(T t) { var t1 = [||](a: t, b: 2); } T t; void Goo() { var t2 = (a: t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } "; var expected = @" using System; using System.Collections.Generic; class Test<T> { void Method(T t) { var t1 = new NewStruct<T>(t, b: 2); } T t; void Goo() { var t2 = new NewStruct<T>(t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } internal struct NewStruct<T> { public T a; public int b; public NewStruct(T a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<T> other && EqualityComparer<T>.Default.Equals(a, other.a) && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out T a, out int b) { a = this.a; b = this.b; } public static implicit operator (T a, int b)(NewStruct<T> value) { return (value.a, value.b); } public static implicit operator NewStruct<T>((T a, int b) value) { return new NewStruct<T>(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task TestCapturedTypeParameter_UpdateType_WithoutUsings(TestHost host) { var text = @" class Test<T> { void Method(T t) { var t1 = [||](a: t, b: 2); } T t; void Goo() { var t2 = (a: t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } "; var expected = @" using System.Collections.Generic; class Test<T> { void Method(T t) { var t1 = new NewStruct<T>(t, b: 2); } T t; void Goo() { var t2 = new NewStruct<T>(t, b: 4); } void Blah<T>(T t) { var t2 = (a: t, b: 4); } } internal struct NewStruct<T> { public T a; public int b; public NewStruct(T a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct<T> other && EqualityComparer<T>.Default.Equals(a, other.a) && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + EqualityComparer<T>.Default.GetHashCode(a); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out T a, out int b) { a = this.a; b = this.b; } public static implicit operator (T a, int b)(NewStruct<T> value) { return (value.a, value.b); } public static implicit operator NewStruct<T>((T a, int b) value) { return new NewStruct<T>(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host, actions: new[] { FeaturesResources.updating_usages_in_containing_member, FeaturesResources.updating_usages_in_containing_type }); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_SinglePart_SingleFile(TestHost host) { var text = @" using System; class Test { void Method() { var t1 = [||](a: 1, b: 2); } void Goo() { var t2 = (a: 3, b: 4); } } class Other { void Method() { var t1 = (a: 1, b: 2); } } "; var expected = @" using System; class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } void Goo() { var t2 = new NewStruct(a: 3, b: 4); } } class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_MultiplePart_SingleFile(TestHost host) { var text = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } class Other { void Method() { var t1 = (a: 1, b: 2); } } "; var expected = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Test { NewStruct Goo() { var t2 = new NewStruct(a: 3, b: 4); return default; } } class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; await TestAsync( text, expected, index: 1, equivalenceKey: Scope.ContainingType.ToString(), options: PreferImplicitTypeWithInfo(), testHost: host); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInType_MultiplePart_MultipleFile(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Test { NewStruct Goo() { var t2 = new NewStruct(a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; await new VerifyCS.Test { TestState = { Sources = { text1, text2, } }, FixedState = { Sources = { expected1, expected2, } }, CodeActionIndex = 1, CodeActionEquivalenceKey = Scope.ContainingType.ToString(), TestHost = host, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion update containing project tests #region update containing project tests [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateAllInProject_MultiplePart_MultipleFile_WithNamespace(TestHost host) { var text1 = @" using System; namespace N { partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } } }"; var text2 = @" using System; partial class Test { (int a, int b) Goo() { var t2 = (a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; namespace N { partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } internal struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } } }"; var expected2 = @" using System; partial class Test { N.NewStruct Goo() { var t2 = new N.NewStruct(a: 3, b: 4); return default; } } partial class Other { void Goo() { var t1 = new N.NewStruct(a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 2, CodeActionEquivalenceKey = Scope.ContainingProject.ToString(), TestHost = host, TestState = { Sources = { text1, text2, }, }, FixedState = { Sources = { expected1, expected2 }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion #region update dependent projects [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateDependentProjects_DirectDependency(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } public struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Other { void Goo() { var t1 = new NewStruct(a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 3, CodeActionEquivalenceKey = Scope.DependentProjects.ToString(), TestHost = host, TestState = { Sources = { text1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { text2 }, AdditionalProjectReferences = { "TestProject" }, } }, }, FixedState = { Sources = { expected1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { expected2 }, AdditionalProjectReferences = { "TestProject" }, } }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } [Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsConvertTupleToStruct)] public async Task UpdateDependentProjects_NoDependency(TestHost host) { var text1 = @" using System; partial class Test { void Method() { var t1 = [||](a: 1, b: 2); } } partial class Other { void Method() { var t1 = (a: 1, b: 2); } }"; var text2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; var expected1 = @" using System; partial class Test { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } partial class Other { void Method() { var t1 = new NewStruct(a: 1, b: 2); } } public struct NewStruct { public int a; public int b; public NewStruct(int a, int b) { this.a = a; this.b = b; } public override bool Equals(object obj) { return obj is NewStruct other && a == other.a && b == other.b; } public override int GetHashCode() { var hashCode = 2118541809; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); return hashCode; } public void Deconstruct(out int a, out int b) { a = this.a; b = this.b; } public static implicit operator (int a, int b)(NewStruct value) { return (value.a, value.b); } public static implicit operator NewStruct((int a, int b) value) { return new NewStruct(value.a, value.b); } }"; var expected2 = @" using System; partial class Other { void Goo() { var t1 = (a: 1, b: 2); } }"; await new VerifyCS.Test { CodeActionIndex = 3, CodeActionEquivalenceKey = Scope.DependentProjects.ToString(), TestHost = host, TestState = { Sources = { text1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { text2 } } }, }, FixedState = { Sources = { expected1 }, AdditionalProjects = { ["DependencyProject"] = { Sources = { expected2 } } }, }, Options = { PreferImplicitTypeWithInfo() }, }.RunAsync(); } #endregion } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/LineSeparators/LineSeparatorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.LineSeparator; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.LineSeparators { [UseExportProvider] public class LineSeparatorTests { [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyFile() => await AssertTagsOnBracesOrSemicolonsAsync(contents: string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyClass() { var file = @"class C { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithOneMethod() { var file = @"class C { void M() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithTwoMethods() { var file = @"class C { void M() { } void N() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithTwoNonEmptyMethods() { var file = @"class C { void M() { N(); } void N() { M(); } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithMethodAndField() { var file = @"class C { void M() { } int field; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyNamespace() { var file = @"namespace N { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndClass() { var file = @"namespace N { class C { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndTwoClasses() { var file = @"namespace N { class C { } class D { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndTwoClassesAndDelegate() { var file = @"namespace N { class C { } class D { } delegate void Del(); }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1, 3); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNestedClass() { var file = @"class C { class N { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestTwoNestedClasses() { var file = @"class C { class N { } class N2 { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestStruct() { var file = @"struct S { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestInterface() { var file = @"interface I { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEnum() { var file = @"enum E { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestProperty() { var file = @"class C { int Prop { get { return 0; } set { } } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestPropertyAndField() { var file = @"class C { int Prop { get { return 0; } set { } } int field; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithFieldAndMethod() { var file = @"class C { int field; void M() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task UsingDirective() { var file = @"using System; class C { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task UsingDirectiveInNamespace() { var file = @"namespace N { using System; class C { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task PropertyStyleEventDeclaration() { var file = @"class C { event EventHandler E { add { } remove { } } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IndexerDeclaration() { var file = @"class C { int this[int i] { get { return i; } set { } } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Constructor() { var file = @"class C { C() { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Destructor() { var file = @"class C { ~C() { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Operator() { var file = @"class C { static C operator +(C lhs, C rhs) { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task ConversionOperator() { var file = @"class C { static implicit operator C(int i) { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Bug930292() { var file = @"class Program { void A() { } void B() { } void C() { } void D() { } } "; await AssertTagsOnBracesOrSemicolonsAsync(file, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Bug930289() { var file = @"namespace Roslyn.Compilers.CSharp { internal struct ArrayElement<T> { internal T Value; internal ArrayElement(T value) { this.Value = value; } public static implicit operator ArrayElement<T>(T value) { return new ArrayElement<T>(value); } } } "; await AssertTagsOnBracesOrSemicolonsAsync(file, 6); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestConsoleApp() { var file = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedProperty() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int Prop => 3; void M() { } }", 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedIndexer() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int this[int i] => 3; void M() { } }", 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedEvent() { // This is not valid code, and parses all wrong, but just in case a user writes it. Note // the 3 is because there is a skipped } in the event declaration. await AssertTagsOnBracesOrSemicolonsAsync(@"class C { event EventHandler MyEvent => 3; void M() { } }", 3); } #region Negative (incomplete) tests [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteClass() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C"); await AssertTagsOnBracesOrSemicolonsAsync(@"class C {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteEnum() { await AssertTagsOnBracesOrSemicolonsAsync(@"enum E"); await AssertTagsOnBracesOrSemicolonsAsync(@"enum E {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteMethod() => await AssertTagsOnBracesOrSemicolonsAsync(@"void goo() {"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteProperty() => await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int P { get; set; void"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteEvent() { await AssertTagsOnBracesOrSemicolonsAsync(@"public event EventHandler"); await AssertTagsOnBracesOrSemicolonsAsync(@"public event EventHandler {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteIndexer() { await AssertTagsOnBracesOrSemicolonsAsync(@"int this[int i]"); await AssertTagsOnBracesOrSemicolonsAsync(@"int this[int i] {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteOperator() { // top level operators not supported in script code await AssertTagsOnBracesOrSemicolonsTokensAsync(@"C operator +(C lhs, C rhs) {", Array.Empty<int>(), Options.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteConversionOperator() => await AssertTagsOnBracesOrSemicolonsAsync(@"implicit operator C(int i) {"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteMember() => await AssertTagsOnBracesOrSemicolonsAsync(@"class C { private !C("); #endregion private static async Task AssertTagsOnBracesOrSemicolonsAsync(string contents, params int[] tokenIndices) { await AssertTagsOnBracesOrSemicolonsTokensAsync(contents, tokenIndices); await AssertTagsOnBracesOrSemicolonsTokensAsync(contents, tokenIndices, Options.Script); } private static async Task AssertTagsOnBracesOrSemicolonsTokensAsync(string contents, int[] tokenIndices, CSharpParseOptions options = null) { using var workspace = TestWorkspace.CreateCSharp(contents, options); var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); var lineSeparatorService = Assert.IsType<CSharpLineSeparatorService>(workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ILineSeparatorService>()); var spans = await lineSeparatorService.GetLineSeparatorsAsync(document, (await document.GetSyntaxRootAsync()).FullSpan, CancellationToken.None); var tokens = (await document.GetSyntaxRootAsync(CancellationToken.None)).DescendantTokens().Where(t => t.Kind() == SyntaxKind.CloseBraceToken || t.Kind() == SyntaxKind.SemicolonToken); Assert.Equal(tokenIndices.Length, spans.Count()); var i = 0; foreach (var span in spans.OrderBy(t => t.Start)) { var expectedToken = tokens.ElementAt(tokenIndices[i]); var expectedSpan = expectedToken.Span; var message = string.Format("Expected to match curly {0} at span {1}. Actual span {2}", tokenIndices[i], expectedSpan, span); Assert.True(expectedSpan == span, message); ++i; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.CSharp.LineSeparator; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.LineSeparators { [UseExportProvider] public class LineSeparatorTests { [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyFile() => await AssertTagsOnBracesOrSemicolonsAsync(contents: string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyClass() { var file = @"class C { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithOneMethod() { var file = @"class C { void M() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithTwoMethods() { var file = @"class C { void M() { } void N() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithTwoNonEmptyMethods() { var file = @"class C { void M() { N(); } void N() { M(); } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithMethodAndField() { var file = @"class C { void M() { } int field; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEmptyNamespace() { var file = @"namespace N { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndClass() { var file = @"namespace N { class C { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndTwoClasses() { var file = @"namespace N { class C { } class D { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNamespaceAndTwoClassesAndDelegate() { var file = @"namespace N { class C { } class D { } delegate void Del(); }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1, 3); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestNestedClass() { var file = @"class C { class N { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestTwoNestedClasses() { var file = @"class C { class N { } class N2 { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestStruct() { var file = @"struct S { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestInterface() { var file = @"interface I { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestEnum() { var file = @"enum E { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestProperty() { var file = @"class C { int Prop { get { return 0; } set { } } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestPropertyAndField() { var file = @"class C { int Prop { get { return 0; } set { } } int field; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestClassWithFieldAndMethod() { var file = @"class C { int field; void M() { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task UsingDirective() { var file = @"using System; class C { }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task UsingDirectiveInNamespace() { var file = @"namespace N { using System; class C { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task UsingDirectiveInFileScopedNamespace() { var file = @"namespace N; using System; class C { } "; await AssertTagsOnBracesOrSemicolonsAsync(file, 1); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task PropertyStyleEventDeclaration() { var file = @"class C { event EventHandler E { add { } remove { } } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IndexerDeclaration() { var file = @"class C { int this[int i] { get { return i; } set { } } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 3, 5); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Constructor() { var file = @"class C { C() { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Destructor() { var file = @"class C { ~C() { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Operator() { var file = @"class C { static C operator +(C lhs, C rhs) { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task ConversionOperator() { var file = @"class C { static implicit operator C(int i) { } int i; }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Bug930292() { var file = @"class Program { void A() { } void B() { } void C() { } void D() { } } "; await AssertTagsOnBracesOrSemicolonsAsync(file, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task Bug930289() { var file = @"namespace Roslyn.Compilers.CSharp { internal struct ArrayElement<T> { internal T Value; internal ArrayElement(T value) { this.Value = value; } public static implicit operator ArrayElement<T>(T value) { return new ArrayElement<T>(value); } } } "; await AssertTagsOnBracesOrSemicolonsAsync(file, 6); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task TestConsoleApp() { var file = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { } }"; await AssertTagsOnBracesOrSemicolonsAsync(file, 2, 4); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedProperty() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int Prop => 3; void M() { } }", 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedIndexer() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int this[int i] => 3; void M() { } }", 0, 2); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] [WorkItem(1297, "https://github.com/dotnet/roslyn/issues/1297")] public async Task ExpressionBodiedEvent() { // This is not valid code, and parses all wrong, but just in case a user writes it. Note // the 3 is because there is a skipped } in the event declaration. await AssertTagsOnBracesOrSemicolonsAsync(@"class C { event EventHandler MyEvent => 3; void M() { } }", 3); } #region Negative (incomplete) tests [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteClass() { await AssertTagsOnBracesOrSemicolonsAsync(@"class C"); await AssertTagsOnBracesOrSemicolonsAsync(@"class C {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteEnum() { await AssertTagsOnBracesOrSemicolonsAsync(@"enum E"); await AssertTagsOnBracesOrSemicolonsAsync(@"enum E {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteMethod() => await AssertTagsOnBracesOrSemicolonsAsync(@"void goo() {"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteProperty() => await AssertTagsOnBracesOrSemicolonsAsync(@"class C { int P { get; set; void"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteEvent() { await AssertTagsOnBracesOrSemicolonsAsync(@"public event EventHandler"); await AssertTagsOnBracesOrSemicolonsAsync(@"public event EventHandler {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteIndexer() { await AssertTagsOnBracesOrSemicolonsAsync(@"int this[int i]"); await AssertTagsOnBracesOrSemicolonsAsync(@"int this[int i] {"); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteOperator() { // top level operators not supported in script code await AssertTagsOnBracesOrSemicolonsTokensAsync(@"C operator +(C lhs, C rhs) {", Array.Empty<int>(), Options.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteConversionOperator() => await AssertTagsOnBracesOrSemicolonsAsync(@"implicit operator C(int i) {"); [Fact, Trait(Traits.Feature, Traits.Features.LineSeparators)] public async Task IncompleteMember() => await AssertTagsOnBracesOrSemicolonsAsync(@"class C { private !C("); #endregion private static async Task AssertTagsOnBracesOrSemicolonsAsync(string contents, params int[] tokenIndices) { await AssertTagsOnBracesOrSemicolonsTokensAsync(contents, tokenIndices); await AssertTagsOnBracesOrSemicolonsTokensAsync(contents, tokenIndices, Options.Script); } private static async Task AssertTagsOnBracesOrSemicolonsTokensAsync(string contents, int[] tokenIndices, CSharpParseOptions? options = null) { using var workspace = TestWorkspace.CreateCSharp(contents, options); var document = workspace.CurrentSolution.GetRequiredDocument(workspace.Documents.First().Id); var root = await document.GetRequiredSyntaxRootAsync(default); var lineSeparatorService = Assert.IsType<CSharpLineSeparatorService>(workspace.Services.GetLanguageServices(LanguageNames.CSharp).GetRequiredService<ILineSeparatorService>()); var spans = await lineSeparatorService.GetLineSeparatorsAsync(document, root.FullSpan, CancellationToken.None); var tokens = root.DescendantTokens().Where(t => t.Kind() is SyntaxKind.CloseBraceToken or SyntaxKind.SemicolonToken); Assert.Equal(tokenIndices.Length, spans.Count()); var i = 0; foreach (var span in spans.OrderBy(t => t.Start)) { var expectedToken = tokens.ElementAt(tokenIndices[i]); var expectedSpan = expectedToken.Span; var message = string.Format("Expected to match curly {0} at span {1}. Actual span {2}", tokenIndices[i], expectedSpan, span); Assert.True(expectedSpan == span, message); ++i; } } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/SimplifyTypeNames/SimplifyTypeNamesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.CSharp.SimplifyTypeNames; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyTypeNames { public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyTypeNamesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new SimplifyTypeNamesCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericName() { await TestInRegularAndScriptAsync( @"using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { var c = [|Goo<int>|](1, 1); } }", @"using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { var c = Goo(1, 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias0() { await TestWithPredefinedTypeOptionsAsync( @"using Goo = System; namespace Root { class A { } class B { public [|Goo::Int32|] a; } }", @"using Goo = System; namespace Root { class A { } class B { public int a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias00() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.IO.File; class A { [|System.IO.File|] c; } }", @"namespace Root { using MyType = System.IO.File; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias00_FileScopedNamespace() { await TestInRegularAndScriptAsync( @"namespace Root; using MyType = System.IO.File; class A { [|System.IO.File|] c; } ", @"namespace Root; using MyType = System.IO.File; class A { MyType c; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias() { var source = @"using MyType = System.Exception; class A { [|System.Exception|] c; }"; await TestInRegularAndScriptAsync(source, @"using MyType = System.Exception; class A { MyType c; }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using MyType = System.Exception; class A { [|System.Exception|] c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias1() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.Exception; class A { [|System.Exception|] c; } }", @"namespace Root { using MyType = System.Exception; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias2() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { class A { [|System.Exception|] c; } }", @"using MyType = System.Exception; namespace Root { class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias3() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { namespace Nested { class A { [|System.Exception|] c; } } }", @"using MyType = System.Exception; namespace Root { namespace Nested { class A { MyType c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias4() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; class A { [|System.Exception|] c; }", @"using MyType = System.Exception; class A { MyType c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias5() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.Exception; class A { [|System.Exception|] c; } }", @"namespace Root { using MyType = System.Exception; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias6() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { class A { [|System.Exception|] c; } }", @"using MyType = System.Exception; namespace Root { class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias7() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { namespace Nested { class A { [|System.Exception|] c; } } }", @"using MyType = System.Exception; namespace Root { namespace Nested { class A { MyType c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias8() { await TestInRegularAndScriptAsync( @"using Goo = System.Int32; namespace Root { namespace Nested { class A { var c = [|System.Int32|].MaxValue; } } }", @"using Goo = System.Int32; namespace Root { namespace Nested { class A { var c = Goo.MaxValue; } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotChangeToAliasInNameOfIfItChangesNameOfName() { await TestInRegularAndScript1Async( @"using System; using Foo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|SimplifyInsideNameof.Program|])); } } }", @"using System; using Foo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Program)); } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName1() { await TestInRegularAndScriptAsync( @"using System; using Goo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|SimplifyInsideNameof.Program|].Main)); } } }", @"using System; using Goo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Goo.Main)); } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName2() { await TestInRegularAndScriptAsync( @"using System; using Goo = N.Goo; namespace N { class Goo { } } namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|N.Goo|])); } } }", @"using System; using Goo = N.Goo; namespace N { class Goo { } } namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Goo)); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliases() { await TestInRegularAndScriptAsync( @"using MyType1 = System.Exception; namespace Root { using MyType2 = Exception; class A { [|System.Exception|] c; } }", @"using MyType1 = System.Exception; namespace Root { using MyType2 = Exception; class A { MyType1 c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliases2() { await TestInRegularAndScriptAsync( @"using MyType1 = System.Exception; namespace Root { using MyType2 = [|System.Exception|]; class A { System.Exception c; } }", @"using MyType1 = System.Exception; namespace Root { using MyType2 = MyType1; class A { System.Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliasesConflict() { await TestMissingInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { using MyType = Exception; class A { [|System.Exception|] c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingOnAmbiguousCref1() { await TestMissingInRegularAndScriptAsync( @" class Example { /// <summary> /// <see cref=""[|Example|].ToString""/> /// </summary> void Method() { } public override string ToString() => throw null; public string ToString(string format, IFormatProvider formatProvider) => throw null; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingOnAmbiguousCref2() { await TestMissingInRegularAndScriptAsync( @" class Example { /// <summary> /// <see cref=""[|Example.ToString|]""/> /// </summary> void Method() { } public override string ToString() => throw null; public string ToString(string format, IFormatProvider formatProvider) => throw null; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingInNameofMemberGroup() { // Note: this is something we could potentially support as removing the // qualification here preserves semantics. await TestMissingInRegularAndScriptAsync( @" class Example { void Method() { _ = nameof([|Example|].Goo); } public static void Goo() { } public static void Goo(int i) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliasesConflict2() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { using MyType = [|System.Exception|]; class A { System.Exception c; } }", @"using MyType = System.Exception; namespace Root { using MyType = MyType; class A { System.Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task AliasInSiblingNamespace() { var content = @"[|namespace Root { namespace Sibling { using MyType = System.Exception; } class A { System.Exception c; } }|]"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task KeywordInt32() { var source = @"class A { [|System.Int32|] i; }"; var featureOptions = PreferIntrinsicTypeEverywhere; await TestInRegularAndScriptAsync(source, @"class A { int i; }", options: featureOptions); await TestActionCountAsync( source, count: 1, parameters: new TestParameters(options: featureOptions)); await TestSpansAsync( @"class A { [|System.Int32|] i; }", parameters: new TestParameters(options: featureOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Keywords() { var builtInTypeMap = new Dictionary<string, string>() { { "System.Boolean", "bool" }, { "System.SByte", "sbyte" }, { "System.Byte", "byte" }, { "System.Decimal", "decimal" }, { "System.Single", "float" }, { "System.Double", "double" }, { "System.Int16", "short" }, { "System.Int32", "int" }, { "System.Int64", "long" }, { "System.Char", "char" }, { "System.String", "string" }, { "System.UInt16", "ushort" }, { "System.UInt32", "uint" }, { "System.UInt64", "ulong" } }; var content = @"class A { [|[||]|] i; } "; foreach (var pair in builtInTypeMap) { var newContent = content.Replace(@"[||]", pair.Key); var expected = content.Replace(@"[||]", pair.Value); await TestWithPredefinedTypeOptionsAsync(newContent, expected); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName() { var content = @"namespace Root { class A { [|System.Exception|] c; } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName1() { var source = @"using System; namespace Root { class A { [|System.Exception|] c; } }"; await TestInRegularAndScriptAsync(source, @"using System; namespace Root { class A { Exception c; } }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using System; namespace Root { class A { [|System|].Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName1_FileScopedNamespace() { var source = @"using System; namespace Root; class A { [|System.Exception|] c; }"; await TestInRegularAndScriptAsync(source, @"using System; namespace Root; class A { Exception c; }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using System; namespace Root; class A { [|System|].Exception c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName2() { await TestInRegularAndScriptAsync( @"namespace System { class A { [|System.Exception|] c; } }", @"namespace System { class A { Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName3() { await TestInRegularAndScriptAsync( @"namespace N1 { public class A1 { } namespace N2 { public class A2 { [|N1.A1|] a; } } }", @"namespace N1 { public class A1 { } namespace N2 { public class A2 { A1 a; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName4() { // this is failing since we can't speculatively bind namespace yet await TestInRegularAndScriptAsync( @"namespace N1 { namespace N2 { public class A1 { } } public class A2 { [|N1.N2.A1|] a; } }", @"namespace N1 { namespace N2 { public class A1 { } } public class A2 { N2.A1 a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName5() { await TestInRegularAndScriptAsync( @"namespace N1 { class NC1 { public class A1 { } } public class A2 { [|N1.NC1.A1|] a; } }", @"namespace N1 { class NC1 { public class A1 { } } public class A2 { NC1.A1 a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName6() { var content = @"namespace N1 { public class A1 { } namespace N2 { public class A1 { } public class A2 { [|N1.A1|] a; } } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName7() { var source = @"namespace N1 { namespace N2 { public class A2 { public class A1 { } [|N1.N2|].A2.A1 a; } } }"; await TestInRegularAndScriptAsync(source, @"namespace N1 { namespace N2 { public class A2 { public class A1 { } A1 a; } } }"); await TestActionCountAsync(source, 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName1() { var content = @"namespace N1 { public class A1 { [|System.EventHandler<System.EventArgs>|] a; } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName2() { var source = @"using System; namespace N1 { public class A1 { [|System.EventHandler<System.EventArgs>|] a; } }"; await TestInRegularAndScriptAsync(source, @"using System; namespace N1 { public class A1 { EventHandler<EventArgs> a; } }"); await TestActionCountAsync(source, 1); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task SimplifyGenericTypeName3() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { public class A1 { {|FixAllInDocument:System.Action|}<System.Action<System.Action<System.EventArgs>, System.Action<System.Action<System.EventArgs, System.Action<System.EventArgs>, System.Action<System.Action<System.Action<System.Action<System.EventArgs>, System.Action<System.EventArgs>>>>>>>> a; } }", @"using System; namespace N1 { public class A1 { Action<Action<Action<EventArgs>, Action<Action<EventArgs, Action<EventArgs>, Action<Action<Action<Action<EventArgs>, Action<EventArgs>>>>>>>> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName4() { var content = @"using MyHandler = System.EventHandler; namespace N1 { public class A1 { [|System.EventHandler<System.EventHandler<System.EventArgs>>|] a; } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName5() { var source = @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<[|System.EventHandler<System.EventArgs>|]> a; } }"; await TestInRegularAndScriptAsync(source, @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<MyHandler> a; } }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<[|System.EventHandler<System.EventArgs>|]> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName6() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { using MyType = N2.A1<Exception>; namespace N2 { public class A1<T> { } } class Test { [|N1.N2.A1<System.Exception>|] a; } }", @"using System; namespace N1 { using MyType = N2.A1<Exception>; namespace N2 { public class A1<T> { } } class Test { MyType a; } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task SimplifyGenericTypeName7() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { using MyType = Exception; namespace N2 { public class A1<T> { } } class Test { N1.N2.A1<[|System.Exception|]> a; } }", @"using System; namespace N1 { using MyType = Exception; namespace N2 { public class A1<T> { } } class Test { N2.A1<MyType> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Array1() { await TestWithPredefinedTypeOptionsAsync( @"using System.Collections.Generic; namespace N1 { class Test { [|System.Collections.Generic.List<System.String[]>|] a; } }", @"using System.Collections.Generic; namespace N1 { class Test { List<string[]> a; } }"); // TODO: The below test is currently disabled due to restrictions of the test framework, this needs to be fixed. //// Test( //// @"using System.Collections.Generic; ////namespace N1 ////{ //// class Test //// { //// System.Collections.Generic.List<[|System.String|][]> a; //// } ////}", @" ////using System.Collections.Generic; ////namespace N1 ////{ //// class Test //// { //// System.Collections.Generic.List<string[]> a; //// } ////}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Array2() { await TestWithPredefinedTypeOptionsAsync( @"using System.Collections.Generic; namespace N1 { class Test { [|System.Collections.Generic.List<System.String[][,][,,,]>|] a; } }", @"using System.Collections.Generic; namespace N1 { class Test { List<string[][,][,,,]> a; } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|Int32|]); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf2() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { var x = nameof([|System.Int32|]); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|Int32|].MaxValue); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldBeOfferedInsideFunctionCalledNameOf() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof(typeof([|Int32|])); } static string nameof(Type t) { return string.Empty; } }", @"using System; class Program { static void Main(string[] args) { var x = nameof(typeof(int)); } static string nameof(Type t) { return string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeNameInsideNameOf() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|System.Int32|]); } }", @"using System; class Program { static void Main(string[] args) { var x = nameof(Int32); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyCrefAliasPredefinedType() { await TestInRegularAndScriptAsync( @"namespace N1 { public class C1 { /// <see cref=""[|System.Int32|]""/> public C1() { } } }", @"namespace N1 { public class C1 { /// <see cref=""int""/> public C1() { } } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias1() { var content = @"using I64 = [|System.Int64|]; namespace N1 { class Test { } }"; await TestMissingInRegularAndScriptAsync(content); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias2() { await TestWithPredefinedTypeOptionsAsync( @"using I64 = System.Int64; using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } }", @"using I64 = System.Int64; using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } }"); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias3() { await TestWithPredefinedTypeOptionsAsync( @"namespace Outer { using I64 = System.Int64; using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } } }", @"namespace Outer { using I64 = System.Int64; using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } } }"); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias4() { await TestWithPredefinedTypeOptionsAsync( @"using I64 = System.Int64; namespace Outer { using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } } }", @"using I64 = System.Int64; namespace Outer { using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } } }"); } [WorkItem(544631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544631")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias5() { var content = @"using System; namespace N { using X = [|System.Nullable<int>|]; }"; var result = @"using System; namespace N { using X = Nullable<int>; }"; await TestInRegularAndScriptAsync(content, result); } [WorkItem(919815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/919815")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyReturnTypeOnMethodCallToAlias() { await TestInRegularAndScriptAsync( @"using alias1 = A; class A { public [|A|] M() { return null; } }", @"using alias1 = A; class A { public alias1 M() { return null; } }"); } [WorkItem(538949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyComplexGeneric1() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class B : A<B> { } class C : I<B>, I<[|B.B|]> { } } interface I<T> { }"); } [WorkItem(538949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyComplexGeneric2() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class B : A<B> { } class C : I<B>, [|B.B|] { } } interface I<T> { }"); } [WorkItem(538991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538991")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMissingOnGeneric() { var content = @"class A<T, S> { class B : [|A<B, B>|] { } }"; await TestMissingInRegularAndScriptAsync(content); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMissingOnUnmentionableTypeParameter1() { var content = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { D.B x = new [|D.B|](); } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyErrorTypeParameter() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using M = System.Collections.Generic.IList<[|System.Collections.Generic.IList<>|]>; class C { }"); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyUnmentionableTypeParameter2() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class D : A<T[]> { } class B { } class C<Y> { D.B x = new [|D.B|](); } }"); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyUnmentionableTypeParameter2_1() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class D : A<T[]> { } class B { } class C<T> { D.B x = new [|D.B|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAlias() { await TestWithPredefinedTypeOptionsAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|global::System|].String s; } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string s; } }"); } [WorkItem(541748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnErrorInScript() { await TestMissingAsync( @"[|Console.WrieLine();|]", new TestParameters(Options.Script)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestConflicts() { await TestInRegularAndScriptAsync( @"namespace OuterNamespace { namespace InnerNamespace { class InnerClass1 { } } class OuterClass1 { OuterNamespace.OuterClass1 M1() { [|OuterNamespace.OuterClass1|] c1; OuterNamespace.OuterClass1.Equals(1, 2); } OuterNamespace.OuterClass2 M2() { OuterNamespace.OuterClass2 c1; OuterNamespace.OuterClass2.Equals(1, 2); } OuterNamespace.InnerNamespace.InnerClass1 M3() { OuterNamespace.InnerNamespace.InnerClass1 c1; OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; global::OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } void OuterClass2() { } void InnerClass1() { } void InnerNamespace() { } } class OuterClass2 { OuterNamespace.OuterClass1 M1() { OuterNamespace.OuterClass1 c1; OuterNamespace.OuterClass1.Equals(1, 2); } OuterNamespace.OuterClass2 M2() { OuterNamespace.OuterClass2 c1; OuterNamespace.OuterClass2.Equals(1, 2); } OuterNamespace.InnerNamespace.InnerClass1 M3() { OuterNamespace.InnerNamespace.InnerClass1 c1; OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; InnerNamespace.InnerClass1.Equals(1, 2); } } }", @"namespace OuterNamespace { namespace InnerNamespace { class InnerClass1 { } } class OuterClass1 { OuterClass1 M1() { OuterClass1 c1; Equals(1, 2); } OuterClass2 M2() { OuterClass2 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } void OuterClass2() { } void InnerClass1() { } void InnerNamespace() { } } class OuterClass2 { OuterClass1 M1() { OuterClass1 c1; Equals(1, 2); } OuterClass2 M2() { OuterClass2 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } } }", index: 1); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationToNameInCurrentScope() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program.Goo.Bar|](); int Goo; } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Program.Goo.Bar(); int Goo; } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationToNameInCurrentScope2() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int Goo) { [|N.Program.Goo.Bar|](); } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int Goo) { Program.Goo.Bar(); } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationToNameInNestedScope() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program.Goo.Bar|](); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationToNameInNestedScope1() { await TestInRegularAndScriptAsync( @"using System.Linq; namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { [|N.Program.Goo.Bar|](); var q = from Goo in args select Goo; } } }", @"using System.Linq; namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { Goo.Bar(); var q = from Goo in args select Goo; } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType1() { await TestMissingInRegularAndScriptAsync( @"class Program<T> { public class Inner { [Bar(typeof([|Program<>.Inner|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType2() { await TestInRegularAndScriptAsync( @"class Program { public class Inner<T> { [Bar(typeof([|Program.Inner<>|]))] void Goo() { } } }", @"class Program { public class Inner<T> { [Bar(typeof(Inner<>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType3() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<>.Inner<>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType4() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType5() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<>.Inner<Y>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType6() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<Y>.Inner<X>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType1() { await TestInRegularAndScriptAsync( @"class Program { public class Inner { [Bar(typeof([|Program.Inner|]))] void Goo() { } } }", @"class Program { public class Inner { [Bar(typeof(Inner))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType2() { await TestInRegularAndScriptAsync( @"class Program<T> { public class Inner { [Bar(typeof([|Program<T>.Inner|]))] void Goo() { } } }", @"class Program<T> { public class Inner { [Bar(typeof(Inner))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType3() { await TestInRegularAndScriptAsync( @"class Program { public class Inner<T> { [Bar(typeof([|Program.Inner<>|]))] void Goo() { } } }", @"class Program { public class Inner<T> { [Bar(typeof(Inner<>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType4() { await TestInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<Y>|]))] void Goo() { } } }", @"class Program<X> { public class Inner<Y> { [Bar(typeof(Inner<Y>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType5() { await TestInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<X>|]))] void Goo() { } } }", @"class Program<X> { public class Inner<Y> { [Bar(typeof(Inner<X>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType6() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<Y>.Inner<Y>|]))] void Goo() { } } }"); } [WorkItem(542650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542650")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestWithInterleavedDirective1() { await TestMissingInRegularAndScriptAsync( @"#if true class A #else class B #endif { class C { } static void Main() { #if true [|A. #else B. #endif C|] x; } }"); } [WorkItem(542719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542719")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalMissing1() { await TestMissingInRegularAndScriptAsync( @"class Program { class System { } int Console = 7; void Main() { string v = null; [|global::System.Console.WriteLine(v)|]; } }"); } [WorkItem(544615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingOnAmbiguousCast() { await TestMissingInRegularAndScriptAsync( @"enum E { } class C { void Main() { var x = ([|global::E|])-1; } }"); } [WorkItem(544616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544616")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ParenthesizeIfParseChanges() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { object x = 1; var y = [|x as System.Nullable<int>|] + 1; } }", @"using System; class C { void M() { object x = 1; var y = (x as int?) + 1; } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification1() { await TestInRegularAndScriptAsync( @"class C { static void Main() { [|System.Nullable<int>.Equals|](1, 1); } }", @"class C { static void Main() { Equals(1, 1); } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification3() { await TestInRegularAndScriptAsync( @"class C { static void Main([|System.Nullable<int>|] i) { } }", @"class C { static void Main(int? i) { } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification4() { await TestWithPredefinedTypeOptionsAsync( @"class C { static void Main([|System.Nullable<System.Int32>|] i) { } }", @"class C { static void Main(int? i) { } }"); } [WorkItem(544977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544977")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification5() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { var x = [|1 is System.Nullable<int>|]? 2 : 3; } }", @"using System; class Program { static void Main() { var x = 1 is int? ? 2 : 3; } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref() { await TestMissingInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""[|Nullable{T}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref2() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""[|System.Nullable{T}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref3() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""[|System.Nullable{T}|].Value""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualTypeParameter() { await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""C{[|Nullable{T}|]}""/> /// </summary> class C<T> { }", @"using System; /// <summary> /// <see cref=""C{T?}""/> /// </summary> class C<T> { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref5() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M{[|Nullable{T}|]}()""/> /// </summary> class A { public void M<U>() where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [WorkItem(40664, "https://github.com/dotnet/roslyn/issues/40664")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_NotAllowedAtTopLevel() { await TestMissingInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""[|Nullable{int}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [WorkItem(40664, "https://github.com/dotnet/roslyn/issues/40664")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_TopLevel2() { await TestInRegularAndScript1Async( @"using System; /// <summary> /// <see cref=""[|System.Nullable{int}|]""/> /// </summary> class A { }", @"using System; /// <summary> /// <see cref=""Nullable{int}""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualType_AsTypeArgument() { // Both the 'original' and 'fixed' code here are incorrect as doc comments do not allow // actual type-references in a type-arg list. await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""C{[|Nullable{int}|]}""/> /// </summary> class C<T> { }", @"using System; /// <summary> /// <see cref=""C{int?}""/> /// </summary> class C<T> { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualType_InParameterList() { await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""Goo([|Nullable{int}|])""/> /// </summary> class C { void Goo(int? i) { } }", @"using System; /// <summary> /// <see cref=""Goo(int?)""/> /// </summary> class C { void Goo(int? i) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref8() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M{[|Nullable{int}|]}()""/> /// </summary> class A { public void M<U>() where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref_Indirect() { await TestInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M([|System.Nullable{A}|])""/> /// </summary> struct A { public void M(A? x) { } }", @"/// <summary> /// <see cref=""A.M(A?)""/> /// </summary> struct A { public void M(A? x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref_Direct() { await TestInRegularAndScriptAsync( @"/// <summary> /// <see cref=""M([|System.Nullable{A}|])""/> /// </summary> struct A { public void M(A? x) { } }", @"/// <summary> /// <see cref=""M(A?)""/> /// </summary> struct A { public void M(A? x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M(List{[|Nullable{int}|]})""/> /// </summary> class A { public void M(List<int?> x) { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M(List{int?})""/> /// </summary> class A { public void M(List<int?> x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{U}(List{[|Nullable{U}|]})""/> /// </summary> class A { public void M<U>(List<U?> x) where U : struct { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{U}(List{U?})""/> /// </summary> class A { public void M<U>(List<U?> x) where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{T}(List{Nullable{T}}, [|Nullable{T}|])""/> /// </summary> class A { public void M<U>(List<U?> x, U? y) where U : struct { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{T}(List{Nullable{T}}, T?)""/> /// </summary> class A { public void M<U>(List<U?> x, U? y) where U : struct { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase1() { await TestInRegularAndScriptAsync( @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { [|N.Color|].Goo(); } }", @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { Color.Goo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase2() { await TestMissingInRegularAndScriptAsync( @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { [|Color.Goo|](); } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase3() { await TestInRegularAndScriptAsync( @"namespace N { class Goo { public static void Bar() { } } /// <summary> /// <see cref=""[|N|].Goo.Bar""/> /// </summary> class Program { public Goo Goo; } }", @"namespace N { class Goo { public static void Bar() { } } /// <summary> /// <see cref=""Goo.Bar""/> /// </summary> class Program { public Goo Goo; } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase4() { await TestInRegularAndScriptAsync( @"namespace N { class Goo { public class Bar { public class Baz { } } } /// <summary> /// <see cref=""[|N|].Goo.Bar.Baz""/> /// </summary> class Program { public Goo Goo; } }", @"namespace N { class Goo { public class Bar { public class Baz { } } } /// <summary> /// <see cref=""Goo.Bar.Baz""/> /// </summary> class Program { public Goo Goo; } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase5() { await TestMissingAsync( @"using A; namespace A { public struct Goo { } } namespace N { /// <summary><see cref=""[|A|].Goo""/></summary class Color { public Goo Goo; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase6() { await TestMissingAsync( @"using System.Reflection.Metadata; using Microsoft.Cci; namespace System.Reflection.Metadata { public enum PrimitiveTypeCode { Void = 1, } } namespace Microsoft.Cci { internal enum PrimitiveTypeCode { NotPrimitive, Pointer, } } namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class TypeSymbol { internal Cci.PrimitiveTypeCode PrimitiveTypeCode => Cci.PrimitiveTypeCode.Pointer; } internal partial class NamedTypeSymbol : TypeSymbol { Cci.PrimitiveTypeCode TypeCode => [|Cci|].PrimitiveTypeCode.NotPrimitive; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAliasQualifiedType() { var source = @"class Program { static void Main() { [|global::Program|] a = null; } }"; await TestAsync(source, @"class Program { static void Main() { Program a = null; } }", parseOptions: null); await TestMissingAsync(source, new TestParameters(GetScriptOptions())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyExpression() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { int x = [|System.Console.Read|]() + System.Console.Read(); } }", @"using System; class Program { static void Main() { int x = Console.Read() + System.Console.Read(); } }"); } [WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyStaticMemberAccess() { var source = @"class Preserve { public static int Y; } class Z<T> : Preserve { } static class M { public static void Main() { int k = [|Z<float>.Y|]; } }"; await TestInRegularAndScriptAsync(source, @"class Preserve { public static int Y; } class Z<T> : Preserve { } static class M { public static void Main() { int k = Preserve.Y; } }"); } [WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyNestedType() { var source = @"class Preserve { public class X { public static int Y; } } class Z<T> : Preserve { } class M { public static void Main() { int k = [|Z<float>.X|].Y; } }"; await TestInRegularAndScriptAsync(source, @"class Preserve { public class X { public static int Y; } } class Z<T> : Preserve { } class M { public static void Main() { int k = Preserve.X.Y; } }"); } [WorkItem(568043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyNamesWhenThereAreParseErrors() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { Console.[||] } }"; await TestMissingInRegularAndScriptAsync(markup); } [WorkItem(566749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|Console.WriteLine|]; } }"); } [WorkItem(566749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|Console.Blah|]; } }"); } [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups3() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|System.Console.WriteLine|]; } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(578686, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task FixAllOccurrences1() { await TestInRegularAndScriptAsync( @"using goo = A.B; using bar = C.D; class Program { static void Main(string[] args) { var s = [|new C.D().prop|]; } } namespace A { class B { } } namespace C { class D { public A.B prop { get; set; } } }", @"using goo = A.B; using bar = C.D; class Program { static void Main(string[] args) { var s = new bar().prop; } } namespace A { class B { } } namespace C { class D { public A.B prop { get; set; } } }"); } [WorkItem(578686, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontUseAlias1() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; namespace NSA { class DuplicateClassName { } } namespace NSB { class DuplicateClassName { } } namespace Test { using AliasA = NSA.DuplicateClassName; using AliasB = NSB.DuplicateClassName; class TestClass { static void Main(string[] args) { var localA = new NSA.DuplicateClassName(); var localB = new NSB.DuplicateClassName(); new List<NoAlias.Goo>().Where(m => [|m.InnocentProperty|] == null); } } } namespace NoAlias { class Goo { public NSB.DuplicateClassName InnocentProperty { get; set; } } }"); } [WorkItem(577169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SuitablyReplaceNullables1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var w = new [|Nullable<>|]. } }"); } [WorkItem(577169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SuitablyReplaceNullables2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = typeof([|Nullable<>|]); } }"); } [WorkItem(608190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608190() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { } } struct S { int x; S(dynamic y) { [|object.Equals|](y, 0); x = y; } }"); } [WorkItem(608190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608190_1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { } } struct S { int x; S(dynamic y) { x = y; [|this.Equals|](y, 0); } }"); } [WorkItem(608932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608932")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608932() { await TestMissingInRegularAndScriptAsync( @"using S = X; class Program { static void Main(string[] args) { } } namespace X { using S = System; enum E { } class C<E> { [|X|].E e; // Simplify type name as suggested } }"); } [WorkItem(635933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635933")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_635933() { await TestMissingInRegularAndScriptAsync( @"using System; class B { public static void Goo(int x, object y) { } static void Main() { C<string>.D.Goo(0); } } class C<T> : B { public class D : C<T> // Start rename session and try to rename D to T { public static void Goo(dynamic x) { Console.WriteLine([|D.Goo(x, "")|]); } } public static string Goo(int x, T y) { string s = null; return s; } }"); } [WorkItem(547246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547246")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task CodeIssueAtRightSpan() { await TestSpansAsync(@" using goo = System.Console; class Program { static void Main(string[] args) { [|System.Console|].Read(); } } "); } [WorkItem(579172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_579172() { await TestMissingInRegularAndScriptAsync( @"class C<T, S> { class D : C<[|D.D|], D.D.D> { } }"); } [WorkItem(633182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_633182() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { ([|this.Goo|])(); } }"); } [WorkItem(627102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627102")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_627102() { await TestMissingInRegularAndScriptAsync( @"using System; class B { static void Goo(int x, object y) { } static void Goo<T>(dynamic x) { Console.WriteLine([|C<T>.Goo|](x, "")); } static void Main() { Goo<string>(0); } } class C<T> : B { public static string Goo(int x, T y) { return ""Hello world""; } }"); } [WorkItem(629572, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotIncludeAliasNameIfLastTargetNameIsTheSame_1() { await TestSpansAsync(@" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new [|System.Collections|].Generic.List<int>(); } } "); await TestInRegularAndScriptAsync( @" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new [|System.Collections|].Generic.List<int>(); } } ", @" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Generic.List<int>(); } } "); } [WorkItem(629572, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotIncludeAliasNameIfLastTargetNameIsTheSame_2() { await TestSpansAsync(@" using Console = System.Console; class Program { static void Main(string[] args) { [|System|].Console.WriteLine(""goo""); } } "); await TestInRegularAndScriptAsync( @" using Console = System.Console; class Program { static void Main(string[] args) { [|System|].Console.WriteLine(""goo""); } } ", @" using Console = System.Console; class Program { static void Main(string[] args) { Console.WriteLine(""goo""); } } "); } [WorkItem(736377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736377")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyTypeNameBrokenCode() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { public static void GetA [[|System.Diagnostics|].CodeAnalysis.SuppressMessage(""Microsoft.Design"", ""CA1024:UsePropertiesWhereAppropriate"")] public static ISet<string> GetAllFilesInSolution() { return null; } }"); } [WorkItem(813385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813385")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyAliases() { await TestMissingInRegularAndScriptAsync( @"using Goo = System.Int32; class C { [|Goo|] f; }"); } [WorkItem(825541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ShowOnlyRelevantSpanForReductionOfGenericName() { await TestSpansAsync(@" namespace A { class Program { static void Main(string[] args) { var x = A.B.OtherClass.Test[|<int>|](5); } } namespace B { class OtherClass { public static int Test<T>(T t) { return 5; } } } }"); } [WorkItem(878773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/878773")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyAttributeNameWithJustAttribute() { await TestMissingInRegularAndScriptAsync( @"[[|Attribute|]] class Attribute : System.Attribute { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ThisQualificationOnFieldOption() { await TestMissingInRegularAndScriptAsync( @"class C { int x; public void z() { [|this|].x = 4; } }", new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue1() { await TestWithPredefinedTypeOptionsAsync( @"class C { [|System.Int32|] x; public void z() { } }", @"class C { int x; public void z() { } }"); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue2() { await TestInRegularAndScriptAsync( @" class C { [|System.Int32|]? x; public void z() { } }", @" class C { int? x; public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_1() { await TestInRegularAndScriptAsync( @" using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", @" using System; class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_2() { await TestInRegularAndScriptAsync( @" class C { /// <see cref=""[|System.Int32|]""/> public void z() { } }", @" class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_3() { await TestInRegularAndScriptAsync( @" using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", @" using System; class C { /// <see cref=""int.MaxValue""/> public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_2() { await TestInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", @"using System; class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_3() { await TestMissingInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_4() { await TestInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", @"using System; class C { /// <see cref=""int.MaxValue""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_5() { await TestMissingInRegularAndScriptAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferMemberAccess() { await TestInRegularAndScriptAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo(int, T[], int, int)""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferDeclaration() { await TestMissingAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", new TestParameters(options: PreferIntrinsicTypeInDeclaration)); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_1() { await TestMissingInRegularAndScriptAsync( @"class C { [|System.Int32|] x; public void z(System.Int32 y) { System.Int32 z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_2() { await TestMissingInRegularAndScriptAsync( @"class C { System.Int32 x; public void z([|System.Int32|] y) { System.Int32 z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_3() { await TestMissingInRegularAndScriptAsync( @"class C { System.Int32 x; public void z(System.Int32 y) { [|System.Int32|] z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_1() { await TestInRegularAndScriptAsync( @"class C { public void z() { var sss = [|System.Int32|].MaxValue; } }", @"class C { public void z() { var sss = int.MaxValue; } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_2() { await TestInRegularAndScriptAsync( @"using System; class C { public void z() { var sss = [|Int32|].MaxValue; } }", @"using System; class C { public void z() { var sss = int.MaxValue; } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(956667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956667")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_3() { await TestMissingInRegularAndScriptAsync( @"using System; class C1 { public static void z() { var sss = [|C2.Memb|].ToString(); } } class C2 { public static int Memb; }"); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_NonDefault_1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { public void z() { var sss = [|Int32|].MaxValue; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_NonDefault_2() { await TestMissingInRegularAndScriptAsync( @"class C { public void z() { var sss = [|System.Int32|].MaxValue; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(965208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965208")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { public void z() { [|System.Console.WriteLine|](""); } }", @" using System; class C { public void z() { Console.WriteLine(""); } }"); await TestInRegularAndScript1Async( @" using System; class C { public void z() { [|System.Int32|] a; } }", @" using System; class C { public void z() { int a; } }", parameters: new TestParameters(options: PreferIntrinsicTypeEverywhere)); } [WorkItem(1019276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019276")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameDoesNotAddUnnecessaryParens() { await TestWithPredefinedTypeOptionsAsync( @"using System; class Program { static void F() { object o = null; if (![|(o is Byte)|]) { } } }", @"using System; class Program { static void F() { object o = null; if (!(o is byte)) { } } }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInPropertyLambda() { await TestWithPredefinedTypeOptionsAsync( @"namespace ClassLibrary2 { public class Class1 { public object X => ([|System.Int32|])0; } }", @"namespace ClassLibrary2 { public class Class1 { public object X => (int)0; } }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInMethodLambda() { await TestWithPredefinedTypeOptionsAsync( @"class C { public string Goo() => ([|System.String|])""; }", @"class C { public string Goo() => (string)""; }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInIndexerLambda() { await TestWithPredefinedTypeOptionsAsync( @"class C { public int this[int index] => ([|System.Int32|])0; }", @"class C { public int this[int index] => (int)0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public async Task SimplifyTypeNameWithOutDiscard() { await TestAsync( @"class C { static void F() { [|C.G|](out _); } static void G(out object o) { o = null; } }", @"class C { static void F() { G(out _); } static void G(out object o) { o = null; } }", parseOptions: CSharpParseOptions.Default); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public async Task SimplifyTypeNameWithOutDiscard_FeatureDisabled() { await TestAsync( @"class C { static void F() { [|C.G|](out _); } static void G(out object o) { o = null; } }", @"class C { static void F() { G(out _); } static void G(out object o) { o = null; } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType1() { await TestAsync( @"using System; class C { void Main() { [|UInt32|] value = UInt32.MaxValue; } }", @"using System; class C { void Main() { uint value = UInt32.MaxValue; } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType2() { await TestAsync( @"using System; class C { void Main() { UInt32 value = [|UInt32|].MaxValue; } }", @"using System; class C { void Main() { UInt32 value = uint.MaxValue; } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType3() { await TestAsync( @"using System; class C { void Main() { [|UInt32|].Parse(""goo""); } }", @"using System; class C { void Main() { uint.Parse(""goo""); } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (string arg in [|args|]) { } } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach ([|string|] arg in args) { } } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [Fact, WorkItem(31849, "https://github.com/dotnet/roslyn/issues/31849")] public async Task NoSuggestionOnNestedNullabilityRequired() { await TestMissingInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { Task<string?> FooAsync() { return Task.FromResult<[|string?|]>(""something""); } }"); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(20377, "https://github.com/dotnet/roslyn/issues/20377")] public async Task TestWarningLevel(int warningLevel) { await TestInRegularAndScriptAsync( @"using System; namespace Root { class A { [|System.Exception|] c; } }", @"using System; namespace Root { class A { Exception c; } }", compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: warningLevel)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingDirective() { await TestInRegularAndScriptAsync( "using [|global::System.IO|];", "using System.IO;"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirective(string typeName) { await TestInRegularAndScriptAsync( $"using My{typeName} = [|global::System.{typeName}|];", $"using My{typeName} = System.{typeName};"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingStaticDirective() { await TestInRegularAndScriptAsync( "using static [|global::System.Math|];", "using static System.Math;"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingDirectiveInNamespace() { await TestInRegularAndScriptAsync( @"using System; namespace N { using [|global::System.IO|]; }", @"using System; namespace N { using System.IO; }"); } [WorkItem(40639, "https://github.com/dotnet/roslyn/issues/40639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestCrefIdAtTopLevel() { await TestDiagnosticInfoAsync( @"/// <summary> /// <see cref=""[|System.String|]""/> /// </summary> class Base { }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); } [WorkItem(40639, "https://github.com/dotnet/roslyn/issues/40639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestCrefIdAtNestedLevel() { await TestDiagnosticInfoAsync( @"/// <summary> /// <see cref=""Foo([|System.String|])""/> /// </summary> class Base { public void Foo(string s) { } }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace(string typeName) { await TestInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|global::System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace_UnboundName(string typeName) { await TestInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|global::System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = System.{typeName}; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingStaticDirectiveInNamespace() { await TestInRegularAndScriptAsync( @"using System; namespace N { using static [|global::System.Math|]; }", @"using System; namespace N { using static System.Math; }"); } [WorkItem(27819, "https://github.com/dotnet/roslyn/issues/27819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred() { await TestInRegularAndScriptAsync( @" class C { void Goo() { [|System.Int32|] i = 0; } }", @" class C { void Goo() { int i = 0; } }", options: PreferImplicitTypeEverywhere); } [WorkItem(27819, "https://github.com/dotnet/roslyn/issues/27819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred_2() { await TestMissingInRegularAndScriptAsync( @" class C { void Goo() { [|int|] i = 0; } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [WorkItem(40647, "https://github.com/dotnet/roslyn/issues/40647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMemberAccessOverPredefinedType() { await TestInRegularAndScript1Async( @"using System; class Base { public void Goo(object o1, object o2) => [|Object|].ReferenceEquals(o1, o2); } ", @"using System; class Base { public void Goo(object o1, object o2) => ReferenceEquals(o1, o2); } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric1() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|System.Collections.Generic.List<int>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric2() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<int>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric3() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<System.Int32>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyIncorrectInstantiation() { await TestMissingAsync( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<string>|] Goo; } "); } [WorkItem(40663, "https://github.com/dotnet/roslyn/issues/40663")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyInTypeOf() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var v = typeof([|Object|]); } } ", @"using System; class C { void Goo() { var v = typeof(object); } } "); } [WorkItem(40876, "https://github.com/dotnet/roslyn/issues/40876")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyPredefinedTypeInUsingDirective1() { await TestWithPredefinedTypeOptionsAsync( @"using System; namespace N { using Alias1 = [|System|].Object; class C { Alias1 a1; } }", @"using System; namespace N { using Alias1 = Object; class C { Alias1 a1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly1() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C|].X""/> /// </summary> class X { } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""X""/> /// </summary> class X { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly2() { await TestSpansAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C|].X""/> /// </summary> class X { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly4() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C.X|].Y(A.B.C.X)""/> /// </summary> class X { void Y(X x) { } } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""Y(X)""/> /// </summary> class X { void Y(X x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly5() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""A.B.C.X.Y([|A.B.C|].X)""/> /// </summary> class X { void Y(X x) { } } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""A.B.C.X.Y(X)""/> /// </summary> class X { void Y(X x) { } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestDoesNotSimplifyUsingAliasDirectiveToPrimitiveType(string typeName) { await TestMissingAsync( $@"using System; namespace N {{ using My{typeName} = [|{typeName}|]; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestSimplifyUsingAliasDirectiveToQualifiedBuiltInType(string typeName) { await TestInRegularAndScript1Async( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestDoesNotSimplifyUsingAliasWithUnboundTypes(string typeName) { await TestMissingInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMemberAccessOffOfObjectKeyword() { await TestInRegularAndScriptAsync( @"using System; class C { bool Goo() { return [|object|].Equals(null, null); } }", @"using System; class C { bool Goo() { return Equals(null, null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallToVirtualInNonSealedClass() { await TestMissingAsync( @"using System; class C { void Goo() { var v = [|base|].GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToVirtualInSealedClass() { await TestInRegularAndScript1Async( @"using System; sealed class C { void Goo() { var v = [|base|].GetHashCode(); } }", @"using System; sealed class C { void Goo() { var v = GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToVirtualInStruct() { await TestInRegularAndScript1Async( @"using System; struct C { void Goo() { var v = [|base|].GetHashCode(); } }", @"using System; struct C { void Goo() { var v = GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallToVirtualWithOverride() { await TestMissingAsync( @"using System; class C { void Goo() { var v = [|base|].GetHashCode(); } public override int GetHashCode() => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToNonVirtual() { await TestInRegularAndScript1Async( @"using System; class Base { public int Baz() => 0; } class C : Base { void Goo() { var v = [|base|].Baz(); } }", @"using System; class Base { public int Baz() => 0; } class C : Base { void Goo() { var v = Baz(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallIfOverloadChanges() { await TestMissingAsync( @"using System; class Base { public int Baz(object o) => 0; } class C : Base { void Goo() { var v = [|base|].Baz(0); } public int Baz(int o) => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyInsideNameof() { await TestMissingAsync( @"using System; class Base { public int Baz(string type) => type switch { nameof([|Int32|]) => 0, }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyInferrableTypeArgumentList() { await TestInRegularAndScript1Async( @"using System; class Base { public void Goo() => Bar[|<int>|](0); public void Bar<T>(T t) => default; } ", @"using System; class Base { public void Goo() => Bar(0); public void Bar<T>(T t) => default; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyNonInferrableTypeArgumentList() { await TestMissingAsync( @"using System; class Base { public void Goo() => Bar[|<int>|](0); public void Bar<T>() => default; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyEnumMemberReferenceInsideEnum() { await TestInRegularAndScript1Async( @" enum E { Goo = 1, Bar = [|E|].Goo, }", @" enum E { Goo = 1, Bar = Goo, }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyEnumMemberReferenceInsideEnumDocComment() { await TestInRegularAndScript1Async( @" /// <summary> /// <see cref=""[|E|].Goo""/> /// </summary> enum E { Goo = 1, }", @" /// <summary> /// <see cref=""Goo""/> /// </summary> enum E { Goo = 1, }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestInstanceMemberReferenceInCref1() { await TestInRegularAndScriptAsync( @" class C { /// <see cref=""[|C.z|]""/> public void z() { } }", @" class C { /// <see cref=""z""/> public void z() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference1() { await TestInRegularAndScript1Async( @"using System; class GooAttribute : Attribute { } [Goo[|Attribute|]] class Bar { } ", @"using System; class GooAttribute : Attribute { } [Goo] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference2() { await TestInRegularAndScript1Async( @"using System; class GooAttribute : Attribute { } [Goo[|Attribute|]()] class Bar { } ", @"using System; class GooAttribute : Attribute { } [Goo()] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference3() { await TestInRegularAndScript1Async( @"using System; namespace N { class GooAttribute : Attribute { } } [N.Goo[|Attribute|]()] class Bar { } ", @"using System; namespace N { class GooAttribute : Attribute { } } [N.Goo()] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference4() { await TestInRegularAndScript1Async( @"using System; namespace N { class GooAttribute : Attribute { } } [N.GooAttribute([|typeof(System.Int32)|])] class Bar { } ", @"using System; namespace N { class GooAttribute : Attribute { } } [N.GooAttribute(typeof(int))] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifySystemAttribute() { await TestInRegularAndScript1Async( @"using System; using System.Runtime.Serialization; namespace Microsoft { [[|System|].Serializable] public struct ClassifiedToken { } }", @"using System; using System.Runtime.Serialization; namespace Microsoft { [Serializable] public struct ClassifiedToken { } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationThatWouldNotCauseConflict1() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program|].Goo.Bar(); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationThatWouldNotCauseConflict2() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|Program|].Goo.Bar(); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationThatWouldCauseConflict1() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N|].Program.Goo.Bar(); int Goo; } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Program.Goo.Bar(); int Goo; } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationThatWouldCauseConflict2() { await TestMissingInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { [|Program|].Goo.Bar(); int Goo; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyPredefinedTypeMemberAccessThatIsInScope() { await TestInRegularAndScript1Async( @"using static System.Int32; class Goo { public void Bar(string a) { var v = [|int|].Parse(a); } }", @"using static System.Int32; class Goo { public void Bar(string a) { var v = Parse(a); } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestDoesNotSimplifyUsingAliasDirectiveToBuiltInType(string typeName) { await TestInRegularAndScript1Async( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity() { await TestMissingInRegularAndScriptAsync( @"using A; using B; namespace A { class Goo { } } namespace B { class Goo { } } class C { void Bar(object o) { var x = ([|A|].Goo)o; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity2() { await TestMissingInRegularAndScriptAsync( @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using B; class C { void Bar(object o) { var x = ([|A|].Goo)o; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationWithoutAmbiguity2() { await TestInRegularAndScript1Async( @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using A; class C { void Bar(object o) { var x = ([|A|].Goo)o; } } }", @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using A; class C { void Bar(object o) { var x = (Goo)o; } } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyCrefAliasPredefinedType_OnClass() { await TestInRegularAndScriptAsync( @"namespace N1 { /// <see cref=""[|System.Int32|]""/> public class C1 { public C1() { } } }", @"namespace N1 { /// <see cref=""int""/> public class C1 { public C1() { } } }", options: PreferIntrinsicTypeEverywhere); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingOnInstanceMemberAccessOfOtherValue() { var content = @" using System; internal struct BitVector : IEquatable<BitVector> { public bool Equals(BitVector other) { } public override bool Equals(object obj) { return obj is BitVector other && Equals(other); } public static bool operator ==(BitVector left, BitVector right) { return [|left|].Equals(right); } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyStaticMemberAccessThroughDerivedType() { var source = @"class Base { public static int Y; } class Derived : Base { } static class M { public static void Main() { int k = [|Derived|].Y; } }"; await TestInRegularAndScriptAsync(source, @"class Base { public static int Y; } class Derived : Base { } static class M { public static void Main() { int k = Base.Y; } }"); } [WorkItem(22493, "https://github.com/dotnet/roslyn/issues/22493")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyCallWithDynamicArg() { await TestInRegularAndScriptAsync( @" using System; class P { public static void Main() { dynamic y = null; [|System|].Console.WriteLine(y); } }", @" using System; class P { public static void Main() { dynamic y = null; Console.WriteLine(y); } }"); } [WorkItem(22493, "https://github.com/dotnet/roslyn/issues/22493")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoSimplifyCallWithDynamicArgWhenCallingThroughDerivedClass() { await TestMissingInRegularAndScriptAsync( @" using System; class Base { public static void Goo(int i) { } } class Derived { } class P { public static void Main() { dynamic y = null; [|Derived|].Goo(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNameofReportsSimplifyMemberAccess() { await TestDiagnosticInfoAsync( @"using System; class Base { void Goo() { var v = nameof([|System|].Int32); } }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, DiagnosticSeverity.Hidden); } [WorkItem(11380, "https://github.com/dotnet/roslyn/issues/11380")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNotOnIllegalInstanceCall() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|Console.Equals|](""""); } }"); } private async Task TestWithPredefinedTypeOptionsAsync(string code, string expected, int index = 0) => await TestInRegularAndScript1Async(code, expected, index, new TestParameters(options: PreferIntrinsicTypeEverywhere)); private OptionsCollection PreferIntrinsicTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithError }, }; private OptionsCollection PreferIntrinsicTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.offWithSilent }, }; private OptionsCollection PreferIntrinsicTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, this.offWithSilent }, }; private OptionsCollection PreferImplicitTypeEverywhere => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> onWithError = new CodeStyleOption2<bool>(true, NotificationOption2.Error); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.CSharp.SimplifyTypeNames; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyTypeNames { public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyTypeNamesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new SimplifyTypeNamesCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericName() { await TestInRegularAndScriptAsync( @"using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { var c = [|Goo<int>|](1, 1); } }", @"using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { var c = Goo(1, 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias0() { await TestWithPredefinedTypeOptionsAsync( @"using Goo = System; namespace Root { class A { } class B { public [|Goo::Int32|] a; } }", @"using Goo = System; namespace Root { class A { } class B { public int a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias00() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.IO.File; class A { [|System.IO.File|] c; } }", @"namespace Root { using MyType = System.IO.File; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias00_FileScopedNamespace() { await TestInRegularAndScriptAsync( @"namespace Root; using MyType = System.IO.File; class A { [|System.IO.File|] c; } ", @"namespace Root; using MyType = System.IO.File; class A { MyType c; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias() { var source = @"using MyType = System.Exception; class A { [|System.Exception|] c; }"; await TestInRegularAndScriptAsync(source, @"using MyType = System.Exception; class A { MyType c; }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using MyType = System.Exception; class A { [|System.Exception|] c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias1() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.Exception; class A { [|System.Exception|] c; } }", @"namespace Root { using MyType = System.Exception; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias2() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { class A { [|System.Exception|] c; } }", @"using MyType = System.Exception; namespace Root { class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias3() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { namespace Nested { class A { [|System.Exception|] c; } } }", @"using MyType = System.Exception; namespace Root { namespace Nested { class A { MyType c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias4() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; class A { [|System.Exception|] c; }", @"using MyType = System.Exception; class A { MyType c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias5() { await TestInRegularAndScriptAsync( @"namespace Root { using MyType = System.Exception; class A { [|System.Exception|] c; } }", @"namespace Root { using MyType = System.Exception; class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias6() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { class A { [|System.Exception|] c; } }", @"using MyType = System.Exception; namespace Root { class A { MyType c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias7() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { namespace Nested { class A { [|System.Exception|] c; } } }", @"using MyType = System.Exception; namespace Root { namespace Nested { class A { MyType c; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task UseAlias8() { await TestInRegularAndScriptAsync( @"using Goo = System.Int32; namespace Root { namespace Nested { class A { var c = [|System.Int32|].MaxValue; } } }", @"using Goo = System.Int32; namespace Root { namespace Nested { class A { var c = Goo.MaxValue; } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotChangeToAliasInNameOfIfItChangesNameOfName() { await TestInRegularAndScript1Async( @"using System; using Foo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|SimplifyInsideNameof.Program|])); } } }", @"using System; using Foo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Program)); } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName1() { await TestInRegularAndScriptAsync( @"using System; using Goo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|SimplifyInsideNameof.Program|].Main)); } } }", @"using System; using Goo = SimplifyInsideNameof.Program; namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Goo.Main)); } } }"); } [WorkItem(21449, "https://github.com/dotnet/roslyn/issues/21449")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoChangeToAliasInNameOfIfItDoesNotAffectName2() { await TestInRegularAndScriptAsync( @"using System; using Goo = N.Goo; namespace N { class Goo { } } namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof([|N.Goo|])); } } }", @"using System; using Goo = N.Goo; namespace N { class Goo { } } namespace SimplifyInsideNameof { class Program { static void Main(string[] args) { Console.WriteLine(nameof(Goo)); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliases() { await TestInRegularAndScriptAsync( @"using MyType1 = System.Exception; namespace Root { using MyType2 = Exception; class A { [|System.Exception|] c; } }", @"using MyType1 = System.Exception; namespace Root { using MyType2 = Exception; class A { MyType1 c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliases2() { await TestInRegularAndScriptAsync( @"using MyType1 = System.Exception; namespace Root { using MyType2 = [|System.Exception|]; class A { System.Exception c; } }", @"using MyType1 = System.Exception; namespace Root { using MyType2 = MyType1; class A { System.Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliasesConflict() { await TestMissingInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { using MyType = Exception; class A { [|System.Exception|] c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingOnAmbiguousCref1() { await TestMissingInRegularAndScriptAsync( @" class Example { /// <summary> /// <see cref=""[|Example|].ToString""/> /// </summary> void Method() { } public override string ToString() => throw null; public string ToString(string format, IFormatProvider formatProvider) => throw null; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingOnAmbiguousCref2() { await TestMissingInRegularAndScriptAsync( @" class Example { /// <summary> /// <see cref=""[|Example.ToString|]""/> /// </summary> void Method() { } public override string ToString() => throw null; public string ToString(string format, IFormatProvider formatProvider) => throw null; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoMissingInNameofMemberGroup() { // Note: this is something we could potentially support as removing the // qualification here preserves semantics. await TestMissingInRegularAndScriptAsync( @" class Example { void Method() { _ = nameof([|Example|].Goo); } public static void Goo() { } public static void Goo(int i) { } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TwoAliasesConflict2() { await TestInRegularAndScriptAsync( @"using MyType = System.Exception; namespace Root { using MyType = [|System.Exception|]; class A { System.Exception c; } }", @"using MyType = System.Exception; namespace Root { using MyType = MyType; class A { System.Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task AliasInSiblingNamespace() { var content = @"[|namespace Root { namespace Sibling { using MyType = System.Exception; } class A { System.Exception c; } }|]"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task KeywordInt32() { var source = @"class A { [|System.Int32|] i; }"; var featureOptions = PreferIntrinsicTypeEverywhere; await TestInRegularAndScriptAsync(source, @"class A { int i; }", options: featureOptions); await TestActionCountAsync( source, count: 1, parameters: new TestParameters(options: featureOptions)); await TestSpansAsync( @"class A { [|System.Int32|] i; }", parameters: new TestParameters(options: featureOptions)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Keywords() { var builtInTypeMap = new Dictionary<string, string>() { { "System.Boolean", "bool" }, { "System.SByte", "sbyte" }, { "System.Byte", "byte" }, { "System.Decimal", "decimal" }, { "System.Single", "float" }, { "System.Double", "double" }, { "System.Int16", "short" }, { "System.Int32", "int" }, { "System.Int64", "long" }, { "System.Char", "char" }, { "System.String", "string" }, { "System.UInt16", "ushort" }, { "System.UInt32", "uint" }, { "System.UInt64", "ulong" } }; var content = @"class A { [|[||]|] i; } "; foreach (var pair in builtInTypeMap) { var newContent = content.Replace(@"[||]", pair.Key); var expected = content.Replace(@"[||]", pair.Value); await TestWithPredefinedTypeOptionsAsync(newContent, expected); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName() { var content = @"namespace Root { class A { [|System.Exception|] c; } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName1() { var source = @"using System; namespace Root { class A { [|System.Exception|] c; } }"; await TestInRegularAndScriptAsync(source, @"using System; namespace Root { class A { Exception c; } }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using System; namespace Root { class A { [|System|].Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName1_FileScopedNamespace() { var source = @"using System; namespace Root; class A { [|System.Exception|] c; }"; await TestInRegularAndScriptAsync(source, @"using System; namespace Root; class A { Exception c; }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using System; namespace Root; class A { [|System|].Exception c; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName2() { await TestInRegularAndScriptAsync( @"namespace System { class A { [|System.Exception|] c; } }", @"namespace System { class A { Exception c; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName3() { await TestInRegularAndScriptAsync( @"namespace N1 { public class A1 { } namespace N2 { public class A2 { [|N1.A1|] a; } } }", @"namespace N1 { public class A1 { } namespace N2 { public class A2 { A1 a; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName4() { // this is failing since we can't speculatively bind namespace yet await TestInRegularAndScriptAsync( @"namespace N1 { namespace N2 { public class A1 { } } public class A2 { [|N1.N2.A1|] a; } }", @"namespace N1 { namespace N2 { public class A1 { } } public class A2 { N2.A1 a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName5() { await TestInRegularAndScriptAsync( @"namespace N1 { class NC1 { public class A1 { } } public class A2 { [|N1.NC1.A1|] a; } }", @"namespace N1 { class NC1 { public class A1 { } } public class A2 { NC1.A1 a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName6() { var content = @"namespace N1 { public class A1 { } namespace N2 { public class A1 { } public class A2 { [|N1.A1|] a; } } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeName7() { var source = @"namespace N1 { namespace N2 { public class A2 { public class A1 { } [|N1.N2|].A2.A1 a; } } }"; await TestInRegularAndScriptAsync(source, @"namespace N1 { namespace N2 { public class A2 { public class A1 { } A1 a; } } }"); await TestActionCountAsync(source, 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName1() { var content = @"namespace N1 { public class A1 { [|System.EventHandler<System.EventArgs>|] a; } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName2() { var source = @"using System; namespace N1 { public class A1 { [|System.EventHandler<System.EventArgs>|] a; } }"; await TestInRegularAndScriptAsync(source, @"using System; namespace N1 { public class A1 { EventHandler<EventArgs> a; } }"); await TestActionCountAsync(source, 1); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task SimplifyGenericTypeName3() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { public class A1 { {|FixAllInDocument:System.Action|}<System.Action<System.Action<System.EventArgs>, System.Action<System.Action<System.EventArgs, System.Action<System.EventArgs>, System.Action<System.Action<System.Action<System.Action<System.EventArgs>, System.Action<System.EventArgs>>>>>>>> a; } }", @"using System; namespace N1 { public class A1 { Action<Action<Action<EventArgs>, Action<Action<EventArgs, Action<EventArgs>, Action<Action<Action<Action<EventArgs>, Action<EventArgs>>>>>>>> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName4() { var content = @"using MyHandler = System.EventHandler; namespace N1 { public class A1 { [|System.EventHandler<System.EventHandler<System.EventArgs>>|] a; } } "; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName5() { var source = @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<[|System.EventHandler<System.EventArgs>|]> a; } }"; await TestInRegularAndScriptAsync(source, @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<MyHandler> a; } }"); await TestActionCountAsync(source, 1); await TestSpansAsync( @"using MyHandler = System.EventHandler<System.EventArgs>; namespace N1 { public class A1 { System.EventHandler<[|System.EventHandler<System.EventArgs>|]> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyGenericTypeName6() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { using MyType = N2.A1<Exception>; namespace N2 { public class A1<T> { } } class Test { [|N1.N2.A1<System.Exception>|] a; } }", @"using System; namespace N1 { using MyType = N2.A1<Exception>; namespace N2 { public class A1<T> { } } class Test { MyType a; } }"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task SimplifyGenericTypeName7() { await TestInRegularAndScriptAsync( @"using System; namespace N1 { using MyType = Exception; namespace N2 { public class A1<T> { } } class Test { N1.N2.A1<[|System.Exception|]> a; } }", @"using System; namespace N1 { using MyType = Exception; namespace N2 { public class A1<T> { } } class Test { N2.A1<MyType> a; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Array1() { await TestWithPredefinedTypeOptionsAsync( @"using System.Collections.Generic; namespace N1 { class Test { [|System.Collections.Generic.List<System.String[]>|] a; } }", @"using System.Collections.Generic; namespace N1 { class Test { List<string[]> a; } }"); // TODO: The below test is currently disabled due to restrictions of the test framework, this needs to be fixed. //// Test( //// @"using System.Collections.Generic; ////namespace N1 ////{ //// class Test //// { //// System.Collections.Generic.List<[|System.String|][]> a; //// } ////}", @" ////using System.Collections.Generic; ////namespace N1 ////{ //// class Test //// { //// System.Collections.Generic.List<string[]> a; //// } ////}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Array2() { await TestWithPredefinedTypeOptionsAsync( @"using System.Collections.Generic; namespace N1 { class Test { [|System.Collections.Generic.List<System.String[][,][,,,]>|] a; } }", @"using System.Collections.Generic; namespace N1 { class Test { List<string[][,][,,,]> a; } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|Int32|]); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf2() { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { var x = nameof([|System.Int32|]); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldNotBeOfferedInsideNameOf3() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|Int32|].MaxValue); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168"), WorkItem(1073099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073099")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyToPredefinedTypeNameShouldBeOfferedInsideFunctionCalledNameOf() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof(typeof([|Int32|])); } static string nameof(Type t) { return string.Empty; } }", @"using System; class Program { static void Main(string[] args) { var x = nameof(typeof(int)); } static string nameof(Type t) { return string.Empty; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyTypeNameInsideNameOf() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = nameof([|System.Int32|]); } }", @"using System; class Program { static void Main(string[] args) { var x = nameof(Int32); } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyCrefAliasPredefinedType() { await TestInRegularAndScriptAsync( @"namespace N1 { public class C1 { /// <see cref=""[|System.Int32|]""/> public C1() { } } }", @"namespace N1 { public class C1 { /// <see cref=""int""/> public C1() { } } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias1() { var content = @"using I64 = [|System.Int64|]; namespace N1 { class Test { } }"; await TestMissingInRegularAndScriptAsync(content); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias2() { await TestWithPredefinedTypeOptionsAsync( @"using I64 = System.Int64; using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } }", @"using I64 = System.Int64; using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } }"); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias3() { await TestWithPredefinedTypeOptionsAsync( @"namespace Outer { using I64 = System.Int64; using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } } }", @"namespace Outer { using I64 = System.Int64; using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } } }"); } [WorkItem(538727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538727")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias4() { await TestWithPredefinedTypeOptionsAsync( @"using I64 = System.Int64; namespace Outer { using Goo = System.Collections.Generic.IList<[|System.Int64|]>; namespace N1 { class Test { } } }", @"using I64 = System.Int64; namespace Outer { using Goo = System.Collections.Generic.IList<long>; namespace N1 { class Test { } } }"); } [WorkItem(544631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544631")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAlias5() { var content = @"using System; namespace N { using X = [|System.Nullable<int>|]; }"; var result = @"using System; namespace N { using X = Nullable<int>; }"; await TestInRegularAndScriptAsync(content, result); } [WorkItem(919815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/919815")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyReturnTypeOnMethodCallToAlias() { await TestInRegularAndScriptAsync( @"using alias1 = A; class A { public [|A|] M() { return null; } }", @"using alias1 = A; class A { public alias1 M() { return null; } }"); } [WorkItem(538949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyComplexGeneric1() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class B : A<B> { } class C : I<B>, I<[|B.B|]> { } } interface I<T> { }"); } [WorkItem(538949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538949")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyComplexGeneric2() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class B : A<B> { } class C : I<B>, [|B.B|] { } } interface I<T> { }"); } [WorkItem(538991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538991")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMissingOnGeneric() { var content = @"class A<T, S> { class B : [|A<B, B>|] { } }"; await TestMissingInRegularAndScriptAsync(content); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMissingOnUnmentionableTypeParameter1() { var content = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { D.B x = new [|D.B|](); } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyErrorTypeParameter() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using M = System.Collections.Generic.IList<[|System.Collections.Generic.IList<>|]>; class C { }"); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [WorkItem(838109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838109")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyUnmentionableTypeParameter2() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class D : A<T[]> { } class B { } class C<Y> { D.B x = new [|D.B|](); } }"); } [WorkItem(539000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539000")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyUnmentionableTypeParameter2_1() { await TestMissingInRegularAndScriptAsync( @"class A<T> { class D : A<T[]> { } class B { } class C<T> { D.B x = new [|D.B|](); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAlias() { await TestWithPredefinedTypeOptionsAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { [|global::System|].String s; } }", @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string s; } }"); } [WorkItem(541748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541748")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnErrorInScript() { await TestMissingAsync( @"[|Console.WrieLine();|]", new TestParameters(Options.Script)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9877"), Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestConflicts() { await TestInRegularAndScriptAsync( @"namespace OuterNamespace { namespace InnerNamespace { class InnerClass1 { } } class OuterClass1 { OuterNamespace.OuterClass1 M1() { [|OuterNamespace.OuterClass1|] c1; OuterNamespace.OuterClass1.Equals(1, 2); } OuterNamespace.OuterClass2 M2() { OuterNamespace.OuterClass2 c1; OuterNamespace.OuterClass2.Equals(1, 2); } OuterNamespace.InnerNamespace.InnerClass1 M3() { OuterNamespace.InnerNamespace.InnerClass1 c1; OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; global::OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } void OuterClass2() { } void InnerClass1() { } void InnerNamespace() { } } class OuterClass2 { OuterNamespace.OuterClass1 M1() { OuterNamespace.OuterClass1 c1; OuterNamespace.OuterClass1.Equals(1, 2); } OuterNamespace.OuterClass2 M2() { OuterNamespace.OuterClass2 c1; OuterNamespace.OuterClass2.Equals(1, 2); } OuterNamespace.InnerNamespace.InnerClass1 M3() { OuterNamespace.InnerNamespace.InnerClass1 c1; OuterNamespace.InnerNamespace.InnerClass1.Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; InnerNamespace.InnerClass1.Equals(1, 2); } } }", @"namespace OuterNamespace { namespace InnerNamespace { class InnerClass1 { } } class OuterClass1 { OuterClass1 M1() { OuterClass1 c1; Equals(1, 2); } OuterClass2 M2() { OuterClass2 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } void OuterClass2() { } void InnerClass1() { } void InnerNamespace() { } } class OuterClass2 { OuterClass1 M1() { OuterClass1 c1; Equals(1, 2); } OuterClass2 M2() { OuterClass2 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } InnerNamespace.InnerClass1 M3() { InnerNamespace.InnerClass1 c1; Equals(1, 2); } } }", index: 1); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationToNameInCurrentScope() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program.Goo.Bar|](); int Goo; } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Program.Goo.Bar(); int Goo; } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationToNameInCurrentScope2() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int Goo) { [|N.Program.Goo.Bar|](); } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int Goo) { Program.Goo.Bar(); } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationToNameInNestedScope() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program.Goo.Bar|](); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationToNameInNestedScope1() { await TestInRegularAndScriptAsync( @"using System.Linq; namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { [|N.Program.Goo.Bar|](); var q = from Goo in args select Goo; } } }", @"using System.Linq; namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { Goo.Bar(); var q = from Goo in args select Goo; } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType1() { await TestMissingInRegularAndScriptAsync( @"class Program<T> { public class Inner { [Bar(typeof([|Program<>.Inner|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType2() { await TestInRegularAndScriptAsync( @"class Program { public class Inner<T> { [Bar(typeof([|Program.Inner<>|]))] void Goo() { } } }", @"class Program { public class Inner<T> { [Bar(typeof(Inner<>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType3() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<>.Inner<>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType4() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType5() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<>.Inner<Y>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnOpenType6() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<Y>.Inner<X>|]))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType1() { await TestInRegularAndScriptAsync( @"class Program { public class Inner { [Bar(typeof([|Program.Inner|]))] void Goo() { } } }", @"class Program { public class Inner { [Bar(typeof(Inner))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType2() { await TestInRegularAndScriptAsync( @"class Program<T> { public class Inner { [Bar(typeof([|Program<T>.Inner|]))] void Goo() { } } }", @"class Program<T> { public class Inner { [Bar(typeof(Inner))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType3() { await TestInRegularAndScriptAsync( @"class Program { public class Inner<T> { [Bar(typeof([|Program.Inner<>|]))] void Goo() { } } }", @"class Program { public class Inner<T> { [Bar(typeof(Inner<>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType4() { await TestInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<Y>|]))] void Goo() { } } }", @"class Program<X> { public class Inner<Y> { [Bar(typeof(Inner<Y>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType5() { await TestInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<X>.Inner<X>|]))] void Goo() { } } }", @"class Program<X> { public class Inner<Y> { [Bar(typeof(Inner<X>))] void Goo() { } } }"); } [WorkItem(541929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541929")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestOnNonOpenType6() { await TestMissingInRegularAndScriptAsync( @"class Program<X> { public class Inner<Y> { [Bar(typeof([|Program<Y>.Inner<Y>|]))] void Goo() { } } }"); } [WorkItem(542650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542650")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestWithInterleavedDirective1() { await TestMissingInRegularAndScriptAsync( @"#if true class A #else class B #endif { class C { } static void Main() { #if true [|A. #else B. #endif C|] x; } }"); } [WorkItem(542719, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542719")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalMissing1() { await TestMissingInRegularAndScriptAsync( @"class Program { class System { } int Console = 7; void Main() { string v = null; [|global::System.Console.WriteLine(v)|]; } }"); } [WorkItem(544615, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544615")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingOnAmbiguousCast() { await TestMissingInRegularAndScriptAsync( @"enum E { } class C { void Main() { var x = ([|global::E|])-1; } }"); } [WorkItem(544616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544616")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ParenthesizeIfParseChanges() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { object x = 1; var y = [|x as System.Nullable<int>|] + 1; } }", @"using System; class C { void M() { object x = 1; var y = (x as int?) + 1; } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification1() { await TestInRegularAndScriptAsync( @"class C { static void Main() { [|System.Nullable<int>.Equals|](1, 1); } }", @"class C { static void Main() { Equals(1, 1); } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification3() { await TestInRegularAndScriptAsync( @"class C { static void Main([|System.Nullable<int>|] i) { } }", @"class C { static void Main(int? i) { } }"); } [WorkItem(544974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544974")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification4() { await TestWithPredefinedTypeOptionsAsync( @"class C { static void Main([|System.Nullable<System.Int32>|] i) { } }", @"class C { static void Main(int? i) { } }"); } [WorkItem(544977, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544977")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplification5() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { var x = [|1 is System.Nullable<int>|]? 2 : 3; } }", @"using System; class Program { static void Main() { var x = 1 is int? ? 2 : 3; } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref() { await TestMissingInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""[|Nullable{T}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref2() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""[|System.Nullable{T}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref3() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""[|System.Nullable{T}|].Value""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualTypeParameter() { await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""C{[|Nullable{T}|]}""/> /// </summary> class C<T> { }", @"using System; /// <summary> /// <see cref=""C{T?}""/> /// </summary> class C<T> { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref5() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M{[|Nullable{T}|]}()""/> /// </summary> class A { public void M<U>() where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [WorkItem(40664, "https://github.com/dotnet/roslyn/issues/40664")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_NotAllowedAtTopLevel() { await TestMissingInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""[|Nullable{int}|]""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [WorkItem(40664, "https://github.com/dotnet/roslyn/issues/40664")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_TopLevel2() { await TestInRegularAndScript1Async( @"using System; /// <summary> /// <see cref=""[|System.Nullable{int}|]""/> /// </summary> class A { }", @"using System; /// <summary> /// <see cref=""Nullable{int}""/> /// </summary> class A { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualType_AsTypeArgument() { // Both the 'original' and 'fixed' code here are incorrect as doc comments do not allow // actual type-references in a type-arg list. await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""C{[|Nullable{int}|]}""/> /// </summary> class C<T> { }", @"using System; /// <summary> /// <see cref=""C{int?}""/> /// </summary> class C<T> { }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableInsideCref_AllowedIfReferencingActualType_InParameterList() { await TestInRegularAndScriptAsync( @"using System; /// <summary> /// <see cref=""Goo([|Nullable{int}|])""/> /// </summary> class C { void Goo(int? i) { } }", @"using System; /// <summary> /// <see cref=""Goo(int?)""/> /// </summary> class C { void Goo(int? i) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingNullableSimplificationInsideCref8() { await TestMissingInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M{[|Nullable{int}|]}()""/> /// </summary> class A { public void M<U>() where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref_Indirect() { await TestInRegularAndScriptAsync( @"/// <summary> /// <see cref=""A.M([|System.Nullable{A}|])""/> /// </summary> struct A { public void M(A? x) { } }", @"/// <summary> /// <see cref=""A.M(A?)""/> /// </summary> struct A { public void M(A? x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref_Direct() { await TestInRegularAndScriptAsync( @"/// <summary> /// <see cref=""M([|System.Nullable{A}|])""/> /// </summary> struct A { public void M(A? x) { } }", @"/// <summary> /// <see cref=""M(A?)""/> /// </summary> struct A { public void M(A? x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M(List{[|Nullable{int}|]})""/> /// </summary> class A { public void M(List<int?> x) { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M(List{int?})""/> /// </summary> class A { public void M(List<int?> x) { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref3() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{U}(List{[|Nullable{U}|]})""/> /// </summary> class A { public void M<U>(List<U?> x) where U : struct { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{U}(List{U?})""/> /// </summary> class A { public void M<U>(List<U?> x) where U : struct { } }"); } [WorkItem(29, "https://github.com/dotnet/roslyn/issues/29")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNullableSimplificationInsideCref4() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{T}(List{Nullable{T}}, [|Nullable{T}|])""/> /// </summary> class A { public void M<U>(List<U?> x, U? y) where U : struct { } }", @"using System; using System.Collections.Generic; /// <summary> /// <see cref=""A.M{T}(List{Nullable{T}}, T?)""/> /// </summary> class A { public void M<U>(List<U?> x, U? y) where U : struct { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase1() { await TestInRegularAndScriptAsync( @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { [|N.Color|].Goo(); } }", @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { Color.Goo(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase2() { await TestMissingInRegularAndScriptAsync( @"using N; namespace N { class Color { public static void Goo() { } public void Bar() { } } } class Program { Color Color; void Main() { [|Color.Goo|](); } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase3() { await TestInRegularAndScriptAsync( @"namespace N { class Goo { public static void Bar() { } } /// <summary> /// <see cref=""[|N|].Goo.Bar""/> /// </summary> class Program { public Goo Goo; } }", @"namespace N { class Goo { public static void Bar() { } } /// <summary> /// <see cref=""Goo.Bar""/> /// </summary> class Program { public Goo Goo; } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase4() { await TestInRegularAndScriptAsync( @"namespace N { class Goo { public class Bar { public class Baz { } } } /// <summary> /// <see cref=""[|N|].Goo.Bar.Baz""/> /// </summary> class Program { public Goo Goo; } }", @"namespace N { class Goo { public class Bar { public class Baz { } } } /// <summary> /// <see cref=""Goo.Bar.Baz""/> /// </summary> class Program { public Goo Goo; } }"); } [WorkItem(40632, "https://github.com/dotnet/roslyn/issues/40632")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase5() { await TestMissingAsync( @"using A; namespace A { public struct Goo { } } namespace N { /// <summary><see cref=""[|A|].Goo""/></summary class Color { public Goo Goo; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestColorColorCase6() { await TestMissingAsync( @"using System.Reflection.Metadata; using Microsoft.Cci; namespace System.Reflection.Metadata { public enum PrimitiveTypeCode { Void = 1, } } namespace Microsoft.Cci { internal enum PrimitiveTypeCode { NotPrimitive, Pointer, } } namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class TypeSymbol { internal Cci.PrimitiveTypeCode PrimitiveTypeCode => Cci.PrimitiveTypeCode.Pointer; } internal partial class NamedTypeSymbol : TypeSymbol { Cci.PrimitiveTypeCode TypeCode => [|Cci|].PrimitiveTypeCode.NotPrimitive; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAliasQualifiedType() { var source = @"class Program { static void Main() { [|global::Program|] a = null; } }"; await TestAsync(source, @"class Program { static void Main() { Program a = null; } }", parseOptions: null); await TestMissingAsync(source, new TestParameters(GetScriptOptions())); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyExpression() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { int x = [|System.Console.Read|]() + System.Console.Read(); } }", @"using System; class Program { static void Main() { int x = Console.Read() + System.Console.Read(); } }"); } [WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyStaticMemberAccess() { var source = @"class Preserve { public static int Y; } class Z<T> : Preserve { } static class M { public static void Main() { int k = [|Z<float>.Y|]; } }"; await TestInRegularAndScriptAsync(source, @"class Preserve { public static int Y; } class Z<T> : Preserve { } static class M { public static void Main() { int k = Preserve.Y; } }"); } [WorkItem(551040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/551040")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyNestedType() { var source = @"class Preserve { public class X { public static int Y; } } class Z<T> : Preserve { } class M { public static void Main() { int k = [|Z<float>.X|].Y; } }"; await TestInRegularAndScriptAsync(source, @"class Preserve { public class X { public static int Y; } } class Z<T> : Preserve { } class M { public static void Main() { int k = Preserve.X.Y; } }"); } [WorkItem(568043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyNamesWhenThereAreParseErrors() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { Console.[||] } }"; await TestMissingInRegularAndScriptAsync(markup); } [WorkItem(566749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|Console.WriteLine|]; } }"); } [WorkItem(566749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566749")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|Console.Blah|]; } }"); } [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMethodGroups3() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main() { Action a = [|System.Console.WriteLine|]; } }", @"using System; class Program { static void Main() { Action a = Console.WriteLine; } }"); } [WorkItem(578686, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task FixAllOccurrences1() { await TestInRegularAndScriptAsync( @"using goo = A.B; using bar = C.D; class Program { static void Main(string[] args) { var s = [|new C.D().prop|]; } } namespace A { class B { } } namespace C { class D { public A.B prop { get; set; } } }", @"using goo = A.B; using bar = C.D; class Program { static void Main(string[] args) { var s = new bar().prop; } } namespace A { class B { } } namespace C { class D { public A.B prop { get; set; } } }"); } [WorkItem(578686, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578686")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontUseAlias1() { await TestMissingInRegularAndScriptAsync( @"using System.Collections.Generic; using System.Linq; namespace NSA { class DuplicateClassName { } } namespace NSB { class DuplicateClassName { } } namespace Test { using AliasA = NSA.DuplicateClassName; using AliasB = NSB.DuplicateClassName; class TestClass { static void Main(string[] args) { var localA = new NSA.DuplicateClassName(); var localB = new NSB.DuplicateClassName(); new List<NoAlias.Goo>().Where(m => [|m.InnocentProperty|] == null); } } } namespace NoAlias { class Goo { public NSB.DuplicateClassName InnocentProperty { get; set; } } }"); } [WorkItem(577169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SuitablyReplaceNullables1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var w = new [|Nullable<>|]. } }"); } [WorkItem(577169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/577169")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SuitablyReplaceNullables2() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { var x = typeof([|Nullable<>|]); } }"); } [WorkItem(608190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608190() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { } } struct S { int x; S(dynamic y) { [|object.Equals|](y, 0); x = y; } }"); } [WorkItem(608190, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608190")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608190_1() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { } } struct S { int x; S(dynamic y) { x = y; [|this.Equals|](y, 0); } }"); } [WorkItem(608932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608932")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_608932() { await TestMissingInRegularAndScriptAsync( @"using S = X; class Program { static void Main(string[] args) { } } namespace X { using S = System; enum E { } class C<E> { [|X|].E e; // Simplify type name as suggested } }"); } [WorkItem(635933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635933")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_635933() { await TestMissingInRegularAndScriptAsync( @"using System; class B { public static void Goo(int x, object y) { } static void Main() { C<string>.D.Goo(0); } } class C<T> : B { public class D : C<T> // Start rename session and try to rename D to T { public static void Goo(dynamic x) { Console.WriteLine([|D.Goo(x, "")|]); } } public static string Goo(int x, T y) { string s = null; return s; } }"); } [WorkItem(547246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547246")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task CodeIssueAtRightSpan() { await TestSpansAsync(@" using goo = System.Console; class Program { static void Main(string[] args) { [|System.Console|].Read(); } } "); } [WorkItem(579172, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579172")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_579172() { await TestMissingInRegularAndScriptAsync( @"class C<T, S> { class D : C<[|D.D|], D.D.D> { } }"); } [WorkItem(633182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633182")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_633182() { await TestMissingInRegularAndScriptAsync( @"class C { void Goo() { ([|this.Goo|])(); } }"); } [WorkItem(627102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627102")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task Bugfix_627102() { await TestMissingInRegularAndScriptAsync( @"using System; class B { static void Goo(int x, object y) { } static void Goo<T>(dynamic x) { Console.WriteLine([|C<T>.Goo|](x, "")); } static void Main() { Goo<string>(0); } } class C<T> : B { public static string Goo(int x, T y) { return ""Hello world""; } }"); } [WorkItem(629572, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotIncludeAliasNameIfLastTargetNameIsTheSame_1() { await TestSpansAsync(@" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new [|System.Collections|].Generic.List<int>(); } } "); await TestInRegularAndScriptAsync( @" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new [|System.Collections|].Generic.List<int>(); } } ", @" using Generic = System.Collections.Generic; class Program { static void Main(string[] args) { var x = new Generic.List<int>(); } } "); } [WorkItem(629572, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/629572")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotIncludeAliasNameIfLastTargetNameIsTheSame_2() { await TestSpansAsync(@" using Console = System.Console; class Program { static void Main(string[] args) { [|System|].Console.WriteLine(""goo""); } } "); await TestInRegularAndScriptAsync( @" using Console = System.Console; class Program { static void Main(string[] args) { [|System|].Console.WriteLine(""goo""); } } ", @" using Console = System.Console; class Program { static void Main(string[] args) { Console.WriteLine(""goo""); } } "); } [WorkItem(736377, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736377")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyTypeNameBrokenCode() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class Program { public static void GetA [[|System.Diagnostics|].CodeAnalysis.SuppressMessage(""Microsoft.Design"", ""CA1024:UsePropertiesWhereAppropriate"")] public static ISet<string> GetAllFilesInSolution() { return null; } }"); } [WorkItem(813385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813385")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyAliases() { await TestMissingInRegularAndScriptAsync( @"using Goo = System.Int32; class C { [|Goo|] f; }"); } [WorkItem(825541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825541")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ShowOnlyRelevantSpanForReductionOfGenericName() { await TestSpansAsync(@" namespace A { class Program { static void Main(string[] args) { var x = A.B.OtherClass.Test[|<int>|](5); } } namespace B { class OtherClass { public static int Test<T>(T t) { return 5; } } } }"); } [WorkItem(878773, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/878773")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DontSimplifyAttributeNameWithJustAttribute() { await TestMissingInRegularAndScriptAsync( @"[[|Attribute|]] class Attribute : System.Attribute { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task ThisQualificationOnFieldOption() { await TestMissingInRegularAndScriptAsync( @"class C { int x; public void z() { [|this|].x = 4; } }", new TestParameters(options: Option(CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue1() { await TestWithPredefinedTypeOptionsAsync( @"class C { [|System.Int32|] x; public void z() { } }", @"class C { int x; public void z() { } }"); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationDefaultValue2() { await TestInRegularAndScriptAsync( @" class C { [|System.Int32|]? x; public void z() { } }", @" class C { int? x; public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_1() { await TestInRegularAndScriptAsync( @" using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", @" using System; class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_2() { await TestInRegularAndScriptAsync( @" class C { /// <see cref=""[|System.Int32|]""/> public void z() { } }", @" class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_Default_3() { await TestInRegularAndScriptAsync( @" using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", @" using System; class C { /// <see cref=""int.MaxValue""/> public void z() { } }", options: PreferIntrinsicTypeEverywhere); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_2() { await TestInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|]""/> public void z() { } }", @"using System; class C { /// <see cref=""int""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_3() { await TestMissingInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_4() { await TestInRegularAndScriptAsync( @"using System; class C { /// <see cref=""[|Int32|].MaxValue""/> public void z() { } }", @"using System; class C { /// <see cref=""int.MaxValue""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_5() { await TestMissingInRegularAndScriptAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferMemberAccess() { await TestInRegularAndScriptAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo(int, T[], int, int)""/> public void z() { } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(954536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954536")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInsideCref_NonDefault_6_PreferDeclaration() { await TestMissingAsync( @"class C { /// <see cref=""System.Collections.Generic.List{T}.CopyTo([|System.Int32|], T[], int, int)""/> public void z() { } }", new TestParameters(options: PreferIntrinsicTypeInDeclaration)); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_1() { await TestMissingInRegularAndScriptAsync( @"class C { [|System.Int32|] x; public void z(System.Int32 y) { System.Int32 z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_2() { await TestMissingInRegularAndScriptAsync( @"class C { System.Int32 x; public void z([|System.Int32|] y) { System.Int32 z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInLocalDeclarationNonDefaultValue_3() { await TestMissingInRegularAndScriptAsync( @"class C { System.Int32 x; public void z(System.Int32 y) { [|System.Int32|] z = 9; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_1() { await TestInRegularAndScriptAsync( @"class C { public void z() { var sss = [|System.Int32|].MaxValue; } }", @"class C { public void z() { var sss = int.MaxValue; } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_2() { await TestInRegularAndScriptAsync( @"using System; class C { public void z() { var sss = [|Int32|].MaxValue; } }", @"using System; class C { public void z() { var sss = int.MaxValue; } }", options: PreferIntrinsicTypeInMemberAccess); } [WorkItem(956667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956667")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_Default_3() { await TestMissingInRegularAndScriptAsync( @"using System; class C1 { public static void z() { var sss = [|C2.Memb|].ToString(); } } class C2 { public static int Memb; }"); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_NonDefault_1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { public void z() { var sss = [|Int32|].MaxValue; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(942568, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942568")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestIntrinsicTypesInMemberAccess_NonDefault_2() { await TestMissingInRegularAndScriptAsync( @"class C { public void z() { var sss = [|System.Int32|].MaxValue; } }", new TestParameters(options: Option(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, false, NotificationOption2.Error))); } [WorkItem(965208, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/965208")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { public void z() { [|System.Console.WriteLine|](""); } }", @" using System; class C { public void z() { Console.WriteLine(""); } }"); await TestInRegularAndScript1Async( @" using System; class C { public void z() { [|System.Int32|] a; } }", @" using System; class C { public void z() { int a; } }", parameters: new TestParameters(options: PreferIntrinsicTypeEverywhere)); } [WorkItem(1019276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019276")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameDoesNotAddUnnecessaryParens() { await TestWithPredefinedTypeOptionsAsync( @"using System; class Program { static void F() { object o = null; if (![|(o is Byte)|]) { } } }", @"using System; class Program { static void F() { object o = null; if (!(o is byte)) { } } }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInPropertyLambda() { await TestWithPredefinedTypeOptionsAsync( @"namespace ClassLibrary2 { public class Class1 { public object X => ([|System.Int32|])0; } }", @"namespace ClassLibrary2 { public class Class1 { public object X => (int)0; } }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInMethodLambda() { await TestWithPredefinedTypeOptionsAsync( @"class C { public string Goo() => ([|System.String|])""; }", @"class C { public string Goo() => (string)""; }"); } [WorkItem(1068445, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1068445")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTypeNameInIndexerLambda() { await TestWithPredefinedTypeOptionsAsync( @"class C { public int this[int index] => ([|System.Int32|])0; }", @"class C { public int this[int index] => (int)0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public async Task SimplifyTypeNameWithOutDiscard() { await TestAsync( @"class C { static void F() { [|C.G|](out _); } static void G(out object o) { o = null; } }", @"class C { static void F() { G(out _); } static void G(out object o) { o = null; } }", parseOptions: CSharpParseOptions.Default); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(388744, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=388744")] public async Task SimplifyTypeNameWithOutDiscard_FeatureDisabled() { await TestAsync( @"class C { static void F() { [|C.G|](out _); } static void G(out object o) { o = null; } }", @"class C { static void F() { G(out _); } static void G(out object o) { o = null; } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType1() { await TestAsync( @"using System; class C { void Main() { [|UInt32|] value = UInt32.MaxValue; } }", @"using System; class C { void Main() { uint value = UInt32.MaxValue; } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInDeclaration); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType2() { await TestAsync( @"using System; class C { void Main() { UInt32 value = [|UInt32|].MaxValue; } }", @"using System; class C { void Main() { UInt32 value = uint.MaxValue; } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(15996, "https://github.com/dotnet/roslyn/issues/15996")] public async Task TestMemberOfBuiltInType3() { await TestAsync( @"using System; class C { void Main() { [|UInt32|].Parse(""goo""); } }", @"using System; class C { void Main() { uint.Parse(""goo""); } }", parseOptions: CSharpParseOptions.Default, options: PreferIntrinsicTypeInMemberAccess); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachCollectionExpression() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (string arg in [|args|]) { } } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [Fact, WorkItem(26923, "https://github.com/dotnet/roslyn/issues/26923")] public async Task NoSuggestionOnForeachType() { await TestMissingInRegularAndScriptAsync( @"using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach ([|string|] arg in args) { } } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [Fact, WorkItem(31849, "https://github.com/dotnet/roslyn/issues/31849")] public async Task NoSuggestionOnNestedNullabilityRequired() { await TestMissingInRegularAndScriptAsync( @"#nullable enable using System.Threading.Tasks; class C { Task<string?> FooAsync() { return Task.FromResult<[|string?|]>(""something""); } }"); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [WorkItem(20377, "https://github.com/dotnet/roslyn/issues/20377")] public async Task TestWarningLevel(int warningLevel) { await TestInRegularAndScriptAsync( @"using System; namespace Root { class A { [|System.Exception|] c; } }", @"using System; namespace Root { class A { Exception c; } }", compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: warningLevel)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingDirective() { await TestInRegularAndScriptAsync( "using [|global::System.IO|];", "using System.IO;"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirective(string typeName) { await TestInRegularAndScriptAsync( $"using My{typeName} = [|global::System.{typeName}|];", $"using My{typeName} = System.{typeName};"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingStaticDirective() { await TestInRegularAndScriptAsync( "using static [|global::System.Math|];", "using static System.Math;"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingDirectiveInNamespace() { await TestInRegularAndScriptAsync( @"using System; namespace N { using [|global::System.IO|]; }", @"using System; namespace N { using System.IO; }"); } [WorkItem(40639, "https://github.com/dotnet/roslyn/issues/40639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestCrefIdAtTopLevel() { await TestDiagnosticInfoAsync( @"/// <summary> /// <see cref=""[|System.String|]""/> /// </summary> class Base { }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); } [WorkItem(40639, "https://github.com/dotnet/roslyn/issues/40639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestCrefIdAtNestedLevel() { await TestDiagnosticInfoAsync( @"/// <summary> /// <see cref=""Foo([|System.String|])""/> /// </summary> class Base { public void Foo(string s) { } }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.PreferBuiltInOrFrameworkTypeDiagnosticId, DiagnosticSeverity.Hidden); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace(string typeName) { await TestInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|global::System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestGlobalAliasSimplifiesInUsingAliasDirectiveWithinNamespace_UnboundName(string typeName) { await TestInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|global::System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = System.{typeName}; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestGlobalAliasSimplifiesInUsingStaticDirectiveInNamespace() { await TestInRegularAndScriptAsync( @"using System; namespace N { using static [|global::System.Math|]; }", @"using System; namespace N { using static System.Math; }"); } [WorkItem(27819, "https://github.com/dotnet/roslyn/issues/27819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred() { await TestInRegularAndScriptAsync( @" class C { void Goo() { [|System.Int32|] i = 0; } }", @" class C { void Goo() { int i = 0; } }", options: PreferImplicitTypeEverywhere); } [WorkItem(27819, "https://github.com/dotnet/roslyn/issues/27819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyToVar_EvenIfVarIsPreferred_2() { await TestMissingInRegularAndScriptAsync( @" class C { void Goo() { [|int|] i = 0; } }", new TestParameters(options: PreferImplicitTypeEverywhere)); } [WorkItem(40647, "https://github.com/dotnet/roslyn/issues/40647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMemberAccessOverPredefinedType() { await TestInRegularAndScript1Async( @"using System; class Base { public void Goo(object o1, object o2) => [|Object|].ReferenceEquals(o1, o2); } ", @"using System; class Base { public void Goo(object o1, object o2) => ReferenceEquals(o1, o2); } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric1() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|System.Collections.Generic.List<int>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric2() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<int>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAliasToGeneric3() { await TestInRegularAndScript1Async( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<System.Int32>|] Goo; } ", @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public MyList Goo; } "); } [WorkItem(40649, "https://github.com/dotnet/roslyn/issues/40649")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyIncorrectInstantiation() { await TestMissingAsync( @"using System.Collections.Generic; using MyList = System.Collections.Generic.List<int>; class Base { public [|List<string>|] Goo; } "); } [WorkItem(40663, "https://github.com/dotnet/roslyn/issues/40663")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyInTypeOf() { await TestInRegularAndScriptAsync( @"using System; class C { void Goo() { var v = typeof([|Object|]); } } ", @"using System; class C { void Goo() { var v = typeof(object); } } "); } [WorkItem(40876, "https://github.com/dotnet/roslyn/issues/40876")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyPredefinedTypeInUsingDirective1() { await TestWithPredefinedTypeOptionsAsync( @"using System; namespace N { using Alias1 = [|System|].Object; class C { Alias1 a1; } }", @"using System; namespace N { using Alias1 = Object; class C { Alias1 a1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly1() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C|].X""/> /// </summary> class X { } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""X""/> /// </summary> class X { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly2() { await TestSpansAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C|].X""/> /// </summary> class X { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly4() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""[|A.B.C.X|].Y(A.B.C.X)""/> /// </summary> class X { void Y(X x) { } } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""Y(X)""/> /// </summary> class X { void Y(X x) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyTopLevelOfCrefOnly5() { await TestInRegularAndScriptAsync( @"using System; namespace A.B.C { /// <summary> /// <see cref=""A.B.C.X.Y([|A.B.C|].X)""/> /// </summary> class X { void Y(X x) { } } }", @"using System; namespace A.B.C { /// <summary> /// <see cref=""A.B.C.X.Y(X)""/> /// </summary> class X { void Y(X x) { } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestDoesNotSimplifyUsingAliasDirectiveToPrimitiveType(string typeName) { await TestMissingAsync( $@"using System; namespace N {{ using My{typeName} = [|{typeName}|]; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestSimplifyUsingAliasDirectiveToQualifiedBuiltInType(string typeName) { await TestInRegularAndScript1Async( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Int8")] [InlineData("UInt8")] [InlineData("Float32")] [InlineData("Float64")] public async Task TestDoesNotSimplifyUsingAliasWithUnboundTypes(string typeName) { await TestMissingInRegularAndScriptAsync( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyMemberAccessOffOfObjectKeyword() { await TestInRegularAndScriptAsync( @"using System; class C { bool Goo() { return [|object|].Equals(null, null); } }", @"using System; class C { bool Goo() { return Equals(null, null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallToVirtualInNonSealedClass() { await TestMissingAsync( @"using System; class C { void Goo() { var v = [|base|].GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToVirtualInSealedClass() { await TestInRegularAndScript1Async( @"using System; sealed class C { void Goo() { var v = [|base|].GetHashCode(); } }", @"using System; sealed class C { void Goo() { var v = GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToVirtualInStruct() { await TestInRegularAndScript1Async( @"using System; struct C { void Goo() { var v = [|base|].GetHashCode(); } }", @"using System; struct C { void Goo() { var v = GetHashCode(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallToVirtualWithOverride() { await TestMissingAsync( @"using System; class C { void Goo() { var v = [|base|].GetHashCode(); } public override int GetHashCode() => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyBaseCallToNonVirtual() { await TestInRegularAndScript1Async( @"using System; class Base { public int Baz() => 0; } class C : Base { void Goo() { var v = [|base|].Baz(); } }", @"using System; class Base { public int Baz() => 0; } class C : Base { void Goo() { var v = Baz(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyBaseCallIfOverloadChanges() { await TestMissingAsync( @"using System; class Base { public int Baz(object o) => 0; } class C : Base { void Goo() { var v = [|base|].Baz(0); } public int Baz(int o) => 0; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyInsideNameof() { await TestMissingAsync( @"using System; class Base { public int Baz(string type) => type switch { nameof([|Int32|]) => 0, }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoSimplifyInferrableTypeArgumentList() { await TestInRegularAndScript1Async( @"using System; class Base { public void Goo() => Bar[|<int>|](0); public void Bar<T>(T t) => default; } ", @"using System; class Base { public void Goo() => Bar(0); public void Bar<T>(T t) => default; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task DoNotSimplifyNonInferrableTypeArgumentList() { await TestMissingAsync( @"using System; class Base { public void Goo() => Bar[|<int>|](0); public void Bar<T>() => default; } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyEnumMemberReferenceInsideEnum() { await TestInRegularAndScript1Async( @" enum E { Goo = 1, Bar = [|E|].Goo, }", @" enum E { Goo = 1, Bar = Goo, }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyEnumMemberReferenceInsideEnumDocComment() { await TestInRegularAndScript1Async( @" /// <summary> /// <see cref=""[|E|].Goo""/> /// </summary> enum E { Goo = 1, }", @" /// <summary> /// <see cref=""Goo""/> /// </summary> enum E { Goo = 1, }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestInstanceMemberReferenceInCref1() { await TestInRegularAndScriptAsync( @" class C { /// <see cref=""[|C.z|]""/> public void z() { } }", @" class C { /// <see cref=""z""/> public void z() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference1() { await TestInRegularAndScript1Async( @"using System; class GooAttribute : Attribute { } [Goo[|Attribute|]] class Bar { } ", @"using System; class GooAttribute : Attribute { } [Goo] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference2() { await TestInRegularAndScript1Async( @"using System; class GooAttribute : Attribute { } [Goo[|Attribute|]()] class Bar { } ", @"using System; class GooAttribute : Attribute { } [Goo()] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference3() { await TestInRegularAndScript1Async( @"using System; namespace N { class GooAttribute : Attribute { } } [N.Goo[|Attribute|]()] class Bar { } ", @"using System; namespace N { class GooAttribute : Attribute { } } [N.Goo()] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyAttributeReference4() { await TestInRegularAndScript1Async( @"using System; namespace N { class GooAttribute : Attribute { } } [N.GooAttribute([|typeof(System.Int32)|])] class Bar { } ", @"using System; namespace N { class GooAttribute : Attribute { } } [N.GooAttribute(typeof(int))] class Bar { } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifySystemAttribute() { await TestInRegularAndScript1Async( @"using System; using System.Runtime.Serialization; namespace Microsoft { [[|System|].Serializable] public struct ClassifiedToken { } }", @"using System; using System.Runtime.Serialization; namespace Microsoft { [Serializable] public struct ClassifiedToken { } }"); } [WorkItem(40633, "https://github.com/dotnet/roslyn/issues/40633")] [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationThatWouldNotCauseConflict1() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N.Program|].Goo.Bar(); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationThatWouldNotCauseConflict2() { await TestInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|Program|].Goo.Bar(); { int Goo; } } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Goo.Bar(); { int Goo; } } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationThatWouldCauseConflict1() { await TestInRegularAndScript1Async( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { [|N|].Program.Goo.Bar(); int Goo; } } }", @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main() { Program.Goo.Bar(); int Goo; } } }"); } [WorkItem(542100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542100")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestPreventSimplificationThatWouldCauseConflict2() { await TestMissingInRegularAndScriptAsync( @"namespace N { class Program { class Goo { public static void Bar() { } } static void Main(int[] args) { [|Program|].Goo.Bar(); int Goo; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyPredefinedTypeMemberAccessThatIsInScope() { await TestInRegularAndScript1Async( @"using static System.Int32; class Goo { public void Bar(string a) { var v = [|int|].Parse(a); } }", @"using static System.Int32; class Goo { public void Bar(string a) { var v = Parse(a); } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] [InlineData("Boolean")] [InlineData("Char")] [InlineData("String")] [InlineData("Int16")] [InlineData("UInt16")] [InlineData("Int32")] [InlineData("UInt32")] [InlineData("Int64")] [InlineData("UInt64")] public async Task TestDoesNotSimplifyUsingAliasDirectiveToBuiltInType(string typeName) { await TestInRegularAndScript1Async( $@"using System; namespace N {{ using My{typeName} = [|System.{typeName}|]; }}", $@"using System; namespace N {{ using My{typeName} = {typeName}; }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity() { await TestMissingInRegularAndScriptAsync( @"using A; using B; namespace A { class Goo { } } namespace B { class Goo { } } class C { void Bar(object o) { var x = ([|A|].Goo)o; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoNotSimplifyIfItWouldIntroduceAmbiguity2() { await TestMissingInRegularAndScriptAsync( @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using B; class C { void Bar(object o) { var x = ([|A|].Goo)o; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestAllowSimplificationWithoutAmbiguity2() { await TestInRegularAndScript1Async( @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using A; class C { void Bar(object o) { var x = ([|A|].Goo)o; } } }", @"using A; namespace A { class Goo { } } namespace B { class Goo { } } namespace N { using A; class C { void Bar(object o) { var x = (Goo)o; } } }"); } [WorkItem(995168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/995168")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task SimplifyCrefAliasPredefinedType_OnClass() { await TestInRegularAndScriptAsync( @"namespace N1 { /// <see cref=""[|System.Int32|]""/> public class C1 { public C1() { } } }", @"namespace N1 { /// <see cref=""int""/> public class C1 { public C1() { } } }", options: PreferIntrinsicTypeEverywhere); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestMissingOnInstanceMemberAccessOfOtherValue() { var content = @" using System; internal struct BitVector : IEquatable<BitVector> { public bool Equals(BitVector other) { } public override bool Equals(object obj) { return obj is BitVector other && Equals(other); } public static bool operator ==(BitVector left, BitVector right) { return [|left|].Equals(right); } }"; await TestMissingInRegularAndScriptAsync(content); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyStaticMemberAccessThroughDerivedType() { var source = @"class Base { public static int Y; } class Derived : Base { } static class M { public static void Main() { int k = [|Derived|].Y; } }"; await TestInRegularAndScriptAsync(source, @"class Base { public static int Y; } class Derived : Base { } static class M { public static void Main() { int k = Base.Y; } }"); } [WorkItem(22493, "https://github.com/dotnet/roslyn/issues/22493")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestSimplifyCallWithDynamicArg() { await TestInRegularAndScriptAsync( @" using System; class P { public static void Main() { dynamic y = null; [|System|].Console.WriteLine(y); } }", @" using System; class P { public static void Main() { dynamic y = null; Console.WriteLine(y); } }"); } [WorkItem(22493, "https://github.com/dotnet/roslyn/issues/22493")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestDoSimplifyCallWithDynamicArgWhenCallingThroughDerivedClass() { await TestMissingInRegularAndScriptAsync( @" using System; class Base { public static void Goo(int i) { } } class Derived { } class P { public static void Main() { dynamic y = null; [|Derived|].Goo(y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNameofReportsSimplifyMemberAccess() { await TestDiagnosticInfoAsync( @"using System; class Base { void Goo() { var v = nameof([|System|].Int32); } }", new OptionsCollection(GetLanguage()), IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, DiagnosticSeverity.Hidden); } [WorkItem(11380, "https://github.com/dotnet/roslyn/issues/11380")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)] public async Task TestNotOnIllegalInstanceCall() { await TestMissingInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { [|Console.Equals|](""""); } }"); } private async Task TestWithPredefinedTypeOptionsAsync(string code, string expected, int index = 0) => await TestInRegularAndScript1Async(code, expected, index, new TestParameters(options: PreferIntrinsicTypeEverywhere)); private OptionsCollection PreferIntrinsicTypeEverywhere => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.onWithError }, }; private OptionsCollection PreferIntrinsicTypeInDeclaration => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, this.offWithSilent }, }; private OptionsCollection PreferIntrinsicTypeInMemberAccess => new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, true, NotificationOption2.Error }, { CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, this.offWithSilent }, }; private OptionsCollection PreferImplicitTypeEverywhere => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithInfo }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithInfo }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithInfo }, }; private readonly CodeStyleOption2<bool> offWithSilent = new CodeStyleOption2<bool>(false, NotificationOption2.Silent); private readonly CodeStyleOption2<bool> onWithInfo = new CodeStyleOption2<bool>(true, NotificationOption2.Suggestion); private readonly CodeStyleOption2<bool> onWithError = new CodeStyleOption2<bool>(true, NotificationOption2.Error); } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/AssemblyKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AssemblyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeNestClass() { await VerifyAbsenceAsync( @"class A { [$$ class B { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo {"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeFileScopedNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() { await VerifyAbsenceAsync( @"$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeAssemblyWithOpenBracket() { await VerifyKeywordAsync( @" [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeClass() { await VerifyKeywordAsync( @" [$$ class Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeInterface() { await VerifyKeywordAsync( @" [$$ interface IGoo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeStruct() { await VerifyKeywordAsync( @" [$$ struct Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeEnum() { await VerifyKeywordAsync( @" [$$ enum Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() { await VerifyAbsenceAsync( @" $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInElementAccess() { await VerifyAbsenceAsync( @"class C { void Goo(string[] array) { array[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInIndex() { await VerifyAbsenceAsync( @"class C { public int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassAssemblyParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateAssemblyParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodAssemblyParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class AssemblyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterAttributeInsideClass() { await VerifyAbsenceAsync( @"class C { [Goo] [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterMethod() { await VerifyAbsenceAsync( @"class C { void Goo() { } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterProperty() { await VerifyAbsenceAsync( @"class C { int Goo { get; } [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterField() { await VerifyAbsenceAsync( @"class C { int Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeAfterEvent() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo; [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInOuterAttribute() { await VerifyKeywordAsync( @"[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeNestClass() { await VerifyAbsenceAsync( @"class A { [$$ class B { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo {"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeFileScopedNamespace() { await VerifyKeywordAsync( @"[$$ namespace Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceWithoutOpenBracket() { await VerifyAbsenceAsync( @"$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeNamespaceAndAfterUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeNamespaceAndAfterGlobalUsingWithNoOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeNamespaceAndAfterUsingWithOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInAttributeBeforeNamespaceAndAfterGlobalUsingWithOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeAssemblyWithOpenBracket() { await VerifyKeywordAsync( @" [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeClass() { await VerifyKeywordAsync( @" [$$ class Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeInterface() { await VerifyKeywordAsync( @" [$$ interface IGoo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeStruct() { await VerifyKeywordAsync( @" [$$ struct Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInAttributeBeforeEnum() { await VerifyKeywordAsync( @" [$$ enum Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeOtherAttributeWithoutOpenBracket() { await VerifyAbsenceAsync( @" $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInAttributeBeforeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyAbsenceAsync( @" global using System; $$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInBeforeAttributeAssemblyAttributeAndAfterGlobalUsingWithoutOpenBracket() { await VerifyKeywordAsync( @" global using System; [$$ [assembly: Whatever] namespace Goo {}"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInOuterAttributeInNamespace() { await VerifyAbsenceAsync( @"namespace Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameterAttribute() { await VerifyAbsenceAsync( @"class C { void Goo([$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInElementAccess() { await VerifyAbsenceAsync( @"class C { void Goo(string[] array) { array[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(362, "https://github.com/dotnet/roslyn/issues/362")] public async Task TestNotInIndex() { await VerifyAbsenceAsync( @"class C { public int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPropertyAttribute() { await VerifyAbsenceAsync( @"class C { int Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEventAttribute() { await VerifyAbsenceAsync( @"class C { event Action<int> Goo { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInClassAssemblyParameters() { await VerifyAbsenceAsync( @"class C<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDelegateAssemblyParameters() { await VerifyAbsenceAsync( @"delegate void D<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethodAssemblyParameters() { await VerifyAbsenceAsync( @"class C { void M<[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInInterface() { await VerifyAbsenceAsync( @"interface I { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInStruct() { await VerifyAbsenceAsync( @"struct S { [$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnum() { await VerifyAbsenceAsync( @"enum E { [$$"); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/ExternKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ExternKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"switch (c) { case 0: [Foo] $$ }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Foo] $$ y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Foo] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterExternInStatement(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword() => await VerifyAbsenceAsync(@"extern $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideNamespace() { await VerifyKeywordAsync( @"namespace N { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N;$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias_InsideNamespace() { await VerifyKeywordAsync( @"namespace N { extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMember_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync( @"class C { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"class C { public $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ExternKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesInSwitchCase(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"switch (c) { case 0: [Foo] $$ }", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterAttributesAndStaticInStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] static $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndReturnStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ return x;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndLocalDeclarationStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ x y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAwaitExpression(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Attr] $$ await bar;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndAssignmentStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Foo] $$ y = bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestBetweenAttributesAndCallStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"[Foo] $$ bar();", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterExternInStatement(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"extern $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword() => await VerifyAbsenceAsync(@"extern $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideNamespace() { await VerifyKeywordAsync( @"namespace N { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N;$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternKeyword_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPreviousExternAlias_InsideNamespace() { await VerifyKeywordAsync( @"namespace N { extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMember_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace_InsideNamespace() { await VerifyAbsenceAsync(@"namespace N { namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync( @"class C { extern $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"class C { public $$"); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AssemblyKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.GetRequiredParent().Kind() == SyntaxKind.AttributeList) { var attributeList = token.GetRequiredParent(); var parentSyntax = attributeList.Parent; switch (parentSyntax) { case CompilationUnitSyntax: case BaseNamespaceDeclarationSyntax: // The case where the parent of attributeList is (Class/Interface/Enum/Struct)DeclarationSyntax, like: // [$$ // class Goo { // for these cases is necessary check if they Parent is CompilationUnitSyntax case BaseTypeDeclarationSyntax baseType when baseType.Parent is CompilationUnitSyntax: // The case where the parent of attributeList is IncompleteMemberSyntax(See test: ), like: // [$$ // for that case is necessary check if they Parent is CompilationUnitSyntax case IncompleteMemberSyntax incompleteMember when incompleteMember.Parent is CompilationUnitSyntax: return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.GetRequiredParent().Kind() == SyntaxKind.AttributeList) { var attributeList = token.GetRequiredParent(); var parentSyntax = attributeList.Parent; switch (parentSyntax) { case CompilationUnitSyntax: case BaseNamespaceDeclarationSyntax: // The case where the parent of attributeList is (Class/Interface/Enum/Struct)DeclarationSyntax, like: // [$$ // class Goo { // for these cases is necessary check if they Parent is CompilationUnitSyntax case BaseTypeDeclarationSyntax baseType when baseType.Parent is CompilationUnitSyntax: // The case where the parent of attributeList is IncompleteMemberSyntax(See test: ), like: // [$$ // for that case is necessary check if they Parent is CompilationUnitSyntax case IncompleteMemberSyntax incompleteMember when incompleteMember.Parent is CompilationUnitSyntax: return true; } } return false; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ExternKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ExternKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; public ExternKeywordRecommender() : base(SyntaxKind.ExternKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return IsExternAliasContext(context) || (context.IsGlobalStatementContext && syntaxTree.IsScript()) || syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsExternAliasContext(CSharpSyntaxContext context) { // cases: // root: | // root: e| // extern alias a; // | // extern alias a; // e| // all the above, but inside a namespace. // usings and other constructs *cannot* precede. var token = context.TargetToken; // root: | if (token.Kind() == SyntaxKind.None) { // root namespace return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // namespace N; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } // extern alias a; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.ExternAliasDirective)) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ExternKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, }; private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, }; private static readonly ISet<SyntaxKind> s_validLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword }; public ExternKeywordRecommender() : base(SyntaxKind.ExternKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return IsExternAliasContext(context) || (context.IsGlobalStatementContext && syntaxTree.IsScript()) || syntaxTree.IsGlobalMemberDeclarationContext(position, s_validGlobalModifiers, cancellationToken) || context.IsMemberDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken) || context.SyntaxTree.IsLocalFunctionDeclarationContext(position, s_validLocalFunctionModifiers, cancellationToken); } private static bool IsExternAliasContext(CSharpSyntaxContext context) { // cases: // root: | // root: e| // extern alias a; // | // extern alias a; // e| // all the above, but inside a namespace. // usings and other constructs *cannot* precede. var token = context.TargetToken; // root: | if (token.Kind() == SyntaxKind.None) { // root namespace return true; } if (token.Kind() == SyntaxKind.OpenBraceToken && token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } // namespace N; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.FileScopedNamespaceDeclaration)) { return true; } // extern alias a; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.ExternAliasDirective)) { return true; } return false; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/ConvertAnonymousTypeToClass/CSharpConvertAnonymousTypeToClassCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass), Shared] internal class CSharpConvertAnonymousTypeToClassCodeRefactoringProvider : AbstractConvertAnonymousTypeToClassCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, ObjectCreationExpressionSyntax, AnonymousObjectCreationExpressionSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertAnonymousTypeToClassCodeRefactoringProvider() { } protected override ObjectCreationExpressionSyntax CreateObjectCreationExpression( NameSyntax nameNode, AnonymousObjectCreationExpressionSyntax anonymousObject) { return SyntaxFactory.ObjectCreationExpression( nameNode, CreateArgumentList(anonymousObject), initializer: null); } private ArgumentListSyntax CreateArgumentList(AnonymousObjectCreationExpressionSyntax anonymousObject) => SyntaxFactory.ArgumentList( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(anonymousObject.OpenBraceToken), CreateArguments(anonymousObject.Initializers), SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(anonymousObject.CloseBraceToken)); private SeparatedSyntaxList<ArgumentSyntax> CreateArguments(SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers) => SyntaxFactory.SeparatedList<ArgumentSyntax>(CreateArguments(OmitTrailingComma(initializers.GetWithSeparators()))); private static SyntaxNodeOrTokenList OmitTrailingComma(SyntaxNodeOrTokenList list) { // Trailing comma is allowed in initializer list, but disallowed in method calls. if (list.Count == 0 || list.Count % 2 == 1) { // The list is either empty, or does not end with a trailing comma. return list; } return list .Replace( list[^2], list[^2].AsNode()! .WithAppendedTrailingTrivia(list[^1].GetLeadingTrivia()) .WithAppendedTrailingTrivia(list[^1].GetTrailingTrivia())) .RemoveAt(list.Count - 1); } private SyntaxNodeOrTokenList CreateArguments(SyntaxNodeOrTokenList list) => new(list.Select(CreateArgumentOrComma)); private SyntaxNodeOrToken CreateArgumentOrComma(SyntaxNodeOrToken declOrComma) => declOrComma.IsToken ? declOrComma : CreateArgument((AnonymousObjectMemberDeclaratorSyntax)declOrComma.AsNode()!); private static ArgumentSyntax CreateArgument(AnonymousObjectMemberDeclaratorSyntax decl) => SyntaxFactory.Argument(decl.Expression); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertAnonymousTypeToClass; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertAnonymousTypeToClass { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertAnonymousTypeToClass), Shared] internal class CSharpConvertAnonymousTypeToClassCodeRefactoringProvider : AbstractConvertAnonymousTypeToClassCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, ObjectCreationExpressionSyntax, AnonymousObjectCreationExpressionSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertAnonymousTypeToClassCodeRefactoringProvider() { } protected override ObjectCreationExpressionSyntax CreateObjectCreationExpression( NameSyntax nameNode, AnonymousObjectCreationExpressionSyntax anonymousObject) { return SyntaxFactory.ObjectCreationExpression( nameNode, CreateArgumentList(anonymousObject), initializer: null); } private ArgumentListSyntax CreateArgumentList(AnonymousObjectCreationExpressionSyntax anonymousObject) => SyntaxFactory.ArgumentList( SyntaxFactory.Token(SyntaxKind.OpenParenToken).WithTriviaFrom(anonymousObject.OpenBraceToken), CreateArguments(anonymousObject.Initializers), SyntaxFactory.Token(SyntaxKind.CloseParenToken).WithTriviaFrom(anonymousObject.CloseBraceToken)); private SeparatedSyntaxList<ArgumentSyntax> CreateArguments(SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers) => SyntaxFactory.SeparatedList<ArgumentSyntax>(CreateArguments(OmitTrailingComma(initializers.GetWithSeparators()))); private static SyntaxNodeOrTokenList OmitTrailingComma(SyntaxNodeOrTokenList list) { // Trailing comma is allowed in initializer list, but disallowed in method calls. if (list.Count == 0 || list.Count % 2 == 1) { // The list is either empty, or does not end with a trailing comma. return list; } return list .Replace( list[^2], list[^2].AsNode()! .WithAppendedTrailingTrivia(list[^1].GetLeadingTrivia()) .WithAppendedTrailingTrivia(list[^1].GetTrailingTrivia())) .RemoveAt(list.Count - 1); } private SyntaxNodeOrTokenList CreateArguments(SyntaxNodeOrTokenList list) => new(list.Select(CreateArgumentOrComma)); private SyntaxNodeOrToken CreateArgumentOrComma(SyntaxNodeOrToken declOrComma) => declOrComma.IsToken ? declOrComma : CreateArgument((AnonymousObjectMemberDeclaratorSyntax)declOrComma.AsNode()!); private static ArgumentSyntax CreateArgument(AnonymousObjectMemberDeclaratorSyntax decl) => SyntaxFactory.Argument(decl.Expression); } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/ConvertTupleToStruct/CSharpConvertTupleToStructCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertTupleToStruct; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ConvertTupleToStruct { [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] [ExportLanguageService(typeof(IConvertTupleToStructCodeRefactoringProvider), LanguageNames.CSharp)] [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertTupleToStruct), Shared] internal class CSharpConvertTupleToStructCodeRefactoringProvider : AbstractConvertTupleToStructCodeRefactoringProvider< ExpressionSyntax, NameSyntax, IdentifierNameSyntax, LiteralExpressionSyntax, ObjectCreationExpressionSyntax, TupleExpressionSyntax, ArgumentSyntax, TupleTypeSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpConvertTupleToStructCodeRefactoringProvider() { } protected override ArgumentSyntax GetArgumentWithChangedName(ArgumentSyntax argument, string name) => argument.WithNameColon(ChangeName(argument.NameColon, name)); private static NameColonSyntax? ChangeName(NameColonSyntax? nameColon, string name) { if (nameColon == null) { return null; } var newName = SyntaxFactory.IdentifierName(name).WithTriviaFrom(nameColon.Name); return nameColon.WithName(newName); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Diagnostics/Analyzers/TypeSyntaxSimplifierWalker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames { internal class TypeSyntaxSimplifierWalker : CSharpSyntaxWalker { private static readonly ImmutableHashSet<string> s_emptyAliasedNames = ImmutableHashSet.Create<string>(StringComparer.Ordinal); /// <summary> /// This set contains the full names of types that have equivalent predefined names in the language. /// </summary> private static readonly ImmutableHashSet<string> s_predefinedTypeMetadataNames = ImmutableHashSet.Create( StringComparer.Ordinal, nameof(Boolean), nameof(SByte), nameof(Byte), nameof(Int16), nameof(UInt16), nameof(Int32), nameof(UInt32), nameof(Int64), nameof(UInt64), nameof(Single), nameof(Double), nameof(Decimal), nameof(String), nameof(Char), nameof(Object)); private readonly CSharpSimplifyTypeNamesDiagnosticAnalyzer _analyzer; private readonly SemanticModel _semanticModel; private readonly OptionSet _optionSet; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _ignoredSpans; private readonly CancellationToken _cancellationToken; private ImmutableArray<Diagnostic>.Builder? _diagnostics; /// <summary> /// Set of type and namespace names that have an alias associated with them. i.e. if the /// user has <c>using X = System.DateTime</c>, then <c>DateTime</c> will be in this set. /// This is used so we can easily tell if we should try to simplify some identifier to an /// alias when we encounter it. /// </summary> private readonly ImmutableHashSet<string> _aliasedNames; public bool HasDiagnostics => _diagnostics?.Count > 0; public ImmutableArray<Diagnostic> Diagnostics => _diagnostics?.ToImmutable() ?? ImmutableArray<Diagnostic>.Empty; public ImmutableArray<Diagnostic>.Builder DiagnosticsBuilder { get { if (_diagnostics is null) Interlocked.CompareExchange(ref _diagnostics, ImmutableArray.CreateBuilder<Diagnostic>(), null); return _diagnostics; } } public TypeSyntaxSimplifierWalker(CSharpSimplifyTypeNamesDiagnosticAnalyzer analyzer, SemanticModel semanticModel, OptionSet optionSet, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? ignoredSpans, CancellationToken cancellationToken) : base(SyntaxWalkerDepth.StructuredTrivia) { _analyzer = analyzer; _semanticModel = semanticModel; _optionSet = optionSet; _ignoredSpans = ignoredSpans; _cancellationToken = cancellationToken; var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); _aliasedNames = GetAliasedNames(root as CompilationUnitSyntax); } private static ImmutableHashSet<string> GetAliasedNames(CompilationUnitSyntax? compilationUnit) { var aliasedNames = s_emptyAliasedNames; if (compilationUnit is null) return aliasedNames; foreach (var usingDirective in compilationUnit.Usings) AddAliasedName(usingDirective); foreach (var member in compilationUnit.Members) { if (member is BaseNamespaceDeclarationSyntax namespaceDeclaration) AddAliasedNames(namespaceDeclaration); } return aliasedNames; void AddAliasedName(UsingDirectiveSyntax usingDirective) { if (usingDirective.Alias is object) { if (usingDirective.Name.GetRightmostName() is IdentifierNameSyntax identifierName) { var identifierAlias = identifierName.Identifier.ValueText; if (!RoslynString.IsNullOrEmpty(identifierAlias)) { aliasedNames = aliasedNames.Add(identifierAlias); } } } } void AddAliasedNames(BaseNamespaceDeclarationSyntax namespaceDeclaration) { foreach (var usingDirective in namespaceDeclaration.Usings) AddAliasedName(usingDirective); foreach (var member in namespaceDeclaration.Members) { if (member is BaseNamespaceDeclarationSyntax memberNamespace) AddAliasedNames(memberNamespace); } } } public override void VisitQualifiedName(QualifiedNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.QualifiedName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.AliasQualifiedName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitGenericName(GenericNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.GenericName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitIdentifierName(IdentifierNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } // Always try to simplify identifiers with an 'Attribute' suffix. // // In other cases, don't bother looking at the right side of A.B or A::B. We will process those in // one of our other top level Visit methods (like VisitQualifiedName). var canTrySimplify = node.Identifier.ValueText.EndsWith("Attribute", StringComparison.Ordinal); if (!canTrySimplify && !node.IsRightSideOfDotOrArrowOrColonColon()) { // The only possible simplifications to an unqualified identifier are replacement with an alias or // replacement with a predefined type. canTrySimplify = CanReplaceIdentifierWithAlias(node.Identifier.ValueText) || CanReplaceIdentifierWithPredefinedType(node.Identifier.ValueText); } if (canTrySimplify && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); return; // Local functions bool CanReplaceIdentifierWithAlias(string identifier) => _aliasedNames.Contains(identifier); static bool CanReplaceIdentifierWithPredefinedType(string identifier) => s_predefinedTypeMetadataNames.Contains(identifier); } public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitQualifiedCref(QualifiedCrefSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } // First, just try to simplify the top-most qualified-cref alone. If we're able to do // this, then there's no need to process it's container. i.e. // // if we have <see cref="A.B.C"/> and we simplify that to <see cref="C"/> there's no // point looking at `A.B`. if (node.IsKind(SyntaxKind.QualifiedCref) && TrySimplify(node)) { // found a match on the qualified cref itself. report it and keep processing. } else { // couldn't simplify the qualified cref itself. descend into the container portion // as that might have portions that can be simplified. Visit(node.Container); } // unilaterally process the member portion of the qualified cref. These may have things // like parameters that could be simplified. i.e. if we have: // // <see cref="A.B.C(X.Y)"/> // // We can simplify both the qualified portion to just `C` and we can simplify the // parameter to just `Y`. Visit(node.Member); } /// <summary> /// This is the root helper that all other TrySimplify methods in this type must call /// through once they think there is a good chance something is simplifiable. It does the /// work of actually going through the real simplification system to validate that the /// simplification is legal and does not affect semantics. /// </summary> private bool TrySimplify(SyntaxNode node) { if (!_analyzer.TrySimplify(_semanticModel, node, out var diagnostic, _optionSet, _cancellationToken)) return false; DiagnosticsBuilder.Add(diagnostic); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames { internal class TypeSyntaxSimplifierWalker : CSharpSyntaxWalker { private static readonly ImmutableHashSet<string> s_emptyAliasedNames = ImmutableHashSet.Create<string>(StringComparer.Ordinal); /// <summary> /// This set contains the full names of types that have equivalent predefined names in the language. /// </summary> private static readonly ImmutableHashSet<string> s_predefinedTypeMetadataNames = ImmutableHashSet.Create( StringComparer.Ordinal, nameof(Boolean), nameof(SByte), nameof(Byte), nameof(Int16), nameof(UInt16), nameof(Int32), nameof(UInt32), nameof(Int64), nameof(UInt64), nameof(Single), nameof(Double), nameof(Decimal), nameof(String), nameof(Char), nameof(Object)); private readonly CSharpSimplifyTypeNamesDiagnosticAnalyzer _analyzer; private readonly SemanticModel _semanticModel; private readonly OptionSet _optionSet; private readonly SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? _ignoredSpans; private readonly CancellationToken _cancellationToken; private ImmutableArray<Diagnostic>.Builder? _diagnostics; /// <summary> /// Set of type and namespace names that have an alias associated with them. i.e. if the /// user has <c>using X = System.DateTime</c>, then <c>DateTime</c> will be in this set. /// This is used so we can easily tell if we should try to simplify some identifier to an /// alias when we encounter it. /// </summary> private readonly ImmutableHashSet<string> _aliasedNames; public bool HasDiagnostics => _diagnostics?.Count > 0; public ImmutableArray<Diagnostic> Diagnostics => _diagnostics?.ToImmutable() ?? ImmutableArray<Diagnostic>.Empty; public ImmutableArray<Diagnostic>.Builder DiagnosticsBuilder { get { if (_diagnostics is null) Interlocked.CompareExchange(ref _diagnostics, ImmutableArray.CreateBuilder<Diagnostic>(), null); return _diagnostics; } } public TypeSyntaxSimplifierWalker(CSharpSimplifyTypeNamesDiagnosticAnalyzer analyzer, SemanticModel semanticModel, OptionSet optionSet, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? ignoredSpans, CancellationToken cancellationToken) : base(SyntaxWalkerDepth.StructuredTrivia) { _analyzer = analyzer; _semanticModel = semanticModel; _optionSet = optionSet; _ignoredSpans = ignoredSpans; _cancellationToken = cancellationToken; var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); _aliasedNames = GetAliasedNames(root as CompilationUnitSyntax); } private static ImmutableHashSet<string> GetAliasedNames(CompilationUnitSyntax? compilationUnit) { var aliasedNames = s_emptyAliasedNames; if (compilationUnit is null) return aliasedNames; foreach (var usingDirective in compilationUnit.Usings) AddAliasedName(usingDirective); foreach (var member in compilationUnit.Members) { if (member is BaseNamespaceDeclarationSyntax namespaceDeclaration) AddAliasedNames(namespaceDeclaration); } return aliasedNames; void AddAliasedName(UsingDirectiveSyntax usingDirective) { if (usingDirective.Alias is object) { if (usingDirective.Name.GetRightmostName() is IdentifierNameSyntax identifierName) { var identifierAlias = identifierName.Identifier.ValueText; if (!RoslynString.IsNullOrEmpty(identifierAlias)) { aliasedNames = aliasedNames.Add(identifierAlias); } } } } void AddAliasedNames(BaseNamespaceDeclarationSyntax namespaceDeclaration) { foreach (var usingDirective in namespaceDeclaration.Usings) AddAliasedName(usingDirective); foreach (var member in namespaceDeclaration.Members) { if (member is BaseNamespaceDeclarationSyntax memberNamespace) AddAliasedNames(memberNamespace); } } } public override void VisitQualifiedName(QualifiedNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.QualifiedName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitAliasQualifiedName(AliasQualifiedNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.AliasQualifiedName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitGenericName(GenericNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.GenericName) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitIdentifierName(IdentifierNameSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } // Always try to simplify identifiers with an 'Attribute' suffix. // // In other cases, don't bother looking at the right side of A.B or A::B. We will process those in // one of our other top level Visit methods (like VisitQualifiedName). var canTrySimplify = node.Identifier.ValueText.EndsWith("Attribute", StringComparison.Ordinal); if (!canTrySimplify && !node.IsRightSideOfDotOrArrowOrColonColon()) { // The only possible simplifications to an unqualified identifier are replacement with an alias or // replacement with a predefined type. canTrySimplify = CanReplaceIdentifierWithAlias(node.Identifier.ValueText) || CanReplaceIdentifierWithPredefinedType(node.Identifier.ValueText); } if (canTrySimplify && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); return; // Local functions bool CanReplaceIdentifierWithAlias(string identifier) => _aliasedNames.Contains(identifier); static bool CanReplaceIdentifierWithPredefinedType(string identifier) => s_predefinedTypeMetadataNames.Contains(identifier); } public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } if (node.IsKind(SyntaxKind.SimpleMemberAccessExpression) && TrySimplify(node)) { // found a match. report it and stop processing. return; } // descend further. DefaultVisit(node); } public override void VisitQualifiedCref(QualifiedCrefSyntax node) { if (_ignoredSpans?.HasIntervalThatOverlapsWith(node.FullSpan.Start, node.FullSpan.Length) ?? false) { return; } // First, just try to simplify the top-most qualified-cref alone. If we're able to do // this, then there's no need to process it's container. i.e. // // if we have <see cref="A.B.C"/> and we simplify that to <see cref="C"/> there's no // point looking at `A.B`. if (node.IsKind(SyntaxKind.QualifiedCref) && TrySimplify(node)) { // found a match on the qualified cref itself. report it and keep processing. } else { // couldn't simplify the qualified cref itself. descend into the container portion // as that might have portions that can be simplified. Visit(node.Container); } // unilaterally process the member portion of the qualified cref. These may have things // like parameters that could be simplified. i.e. if we have: // // <see cref="A.B.C(X.Y)"/> // // We can simplify both the qualified portion to just `C` and we can simplify the // parameter to just `Y`. Visit(node.Member); } /// <summary> /// This is the root helper that all other TrySimplify methods in this type must call /// through once they think there is a good chance something is simplifiable. It does the /// work of actually going through the real simplification system to validate that the /// simplification is legal and does not affect semantics. /// </summary> private bool TrySimplify(SyntaxNode node) { if (!_analyzer.TrySimplify(_semanticModel, node, out var diagnostic, _optionSet, _cancellationToken)) return false; DiagnosticsBuilder.Add(diagnostic); return true; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is NamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is NamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/MethodGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class MethodGenerator { internal static BaseNamespaceDeclarationSyntax AddMethodTo( BaseNamespaceDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.Namespace, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static CompilationUnitSyntax AddMethodTo( CompilationUnitSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var declaration = GenerateMethodDeclaration( method, CodeGenerationDestination.CompilationUnit, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, declaration, options, availableIndices, after: LastMethod); return destination.WithMembers(members.ToSyntaxList()); } internal static TypeDeclarationSyntax AddMethodTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateMethodDeclaration( method, GetDestination(destination), options, destination?.SyntaxTree.Options ?? options.ParseOptions); // Create a clone of the original type with the new method inserted. var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod); return AddMembersTo(destination, members); } public static MethodDeclarationSyntax GenerateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<MethodDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateMethodDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } public static LocalFunctionStatementSyntax GenerateLocalFunctionDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { options ??= CodeGenerationOptions.Default; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<LocalFunctionStatementSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var declaration = GenerateLocalFunctionDeclarationWorker( method, destination, options, parseOptions); return AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options)); } private static MethodDeclarationSyntax GenerateMethodDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { // Don't rely on destination to decide if method body should be generated. // Users of this service need to express their intention explicitly, either by // setting `CodeGenerationOptions.GenerateMethodBodies` to true, or making // `method` abstract. This would provide more flexibility. var hasNoBody = !options.GenerateMethodBodies || method.IsAbstract; var explicitInterfaceSpecifier = GenerateExplicitInterfaceSpecifier(method.ExplicitInterfaceImplementations); var methodDeclaration = SyntaxFactory.MethodDeclaration( attributeLists: GenerateAttributes(method, options, explicitInterfaceSpecifier != null), modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), explicitInterfaceSpecifier: explicitInterfaceSpecifier, identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, explicitInterfaceSpecifier != null, options), constraintClauses: GenerateConstraintClauses(method), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); methodDeclaration = UseExpressionBodyIfDesired(options, methodDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(methodDeclaration); } private static LocalFunctionStatementSyntax GenerateLocalFunctionDeclarationWorker( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options, ParseOptions parseOptions) { var localFunctionDeclaration = SyntaxFactory.LocalFunctionStatement( modifiers: GenerateModifiers(method, destination, options), returnType: method.GenerateReturnTypeSyntax(), identifier: method.Name.ToIdentifierToken(), typeParameterList: GenerateTypeParameterList(method, options), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options), constraintClauses: GenerateConstraintClauses(method), body: StatementGenerator.GenerateBlock(method), expressionBody: null, semicolonToken: default); localFunctionDeclaration = UseExpressionBodyIfDesired(options, localFunctionDeclaration, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(localFunctionDeclaration); } private static MethodDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, MethodDeclarationSyntax methodDeclaration, ParseOptions parseOptions) { if (methodDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods).Value; if (methodDeclaration.Body.TryConvertToArrowExpressionBody( methodDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return methodDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return methodDeclaration; } private static LocalFunctionStatementSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, LocalFunctionStatementSyntax localFunctionDeclaration, ParseOptions parseOptions) { if (localFunctionDeclaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions).Value; if (localFunctionDeclaration.Body.TryConvertToArrowExpressionBody( localFunctionDeclaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return localFunctionDeclaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return localFunctionDeclaration; } private static SyntaxList<AttributeListSyntax> GenerateAttributes( IMethodSymbol method, CodeGenerationOptions options, bool isExplicit) { var attributes = new List<AttributeListSyntax>(); if (!isExplicit) { attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options)); attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword))); } return attributes.ToSyntaxList(); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses( IMethodSymbol method) { return !method.ExplicitInterfaceImplementations.Any() && !method.IsOverride ? method.TypeParameters.GenerateConstraintClauses() : default; } private static TypeParameterListSyntax GenerateTypeParameterList( IMethodSymbol method, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(method.TypeParameters, options); } private static SyntaxTokenList GenerateModifiers( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); // Only "static" and "unsafe" modifiers allowed if we're an explicit impl. if (method.ExplicitInterfaceImplementations.Any()) { if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } } else { // If we're generating into an interface, then we don't use any modifiers. if (destination != CodeGenerationDestination.CompilationUnit && destination != CodeGenerationDestination.Namespace && destination != CodeGenerationDestination.InterfaceType) { AddAccessibilityModifiers(method.DeclaredAccessibility, tokens, options, Accessibility.Private); if (method.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } if (method.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (method.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } // Don't show the readonly modifier if the containing type is already readonly // ContainingSymbol is used to guard against methods which are not members of their ContainingType (e.g. lambdas and local functions) if (method.IsReadOnly && (method.ContainingSymbol as INamedTypeSymbol)?.IsReadOnly != true) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (method.IsOverride) { tokens.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); } if (method.IsVirtual) { tokens.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); } if (CodeGenerationMethodInfo.GetIsPartial(method) && !method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } } if (CodeGenerationMethodInfo.GetIsUnsafe(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); } if (CodeGenerationMethodInfo.GetIsNew(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); } } if (destination != CodeGenerationDestination.InterfaceType) { if (CodeGenerationMethodInfo.GetIsAsyncMethod(method)) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); } } if (CodeGenerationMethodInfo.GetIsPartial(method) && method.IsAsync) { tokens.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/NamedTypeGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamedTypeGenerator { public static TypeDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, TypeDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return AddMembersTo(destination, members); } public static BaseNamespaceDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return ConditionallyAddFormattingAnnotationTo( destination.WithMembers(members), members); } public static CompilationUnitSyntax AddNamedTypeTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return destination.WithMembers(members); } public static MemberDeclarationSyntax GenerateNamedTypeDeclaration( ICodeGenerationService service, INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; var declaration = GetDeclarationSyntaxWithoutMembers(namedType, destination, options); // If we are generating members then make sure to exclude properties that cannot be generated. // Reason: Calling AddProperty on a propertysymbol that can't be generated (like one with params) causes // the getter and setter to get generated instead. Since the list of members is going to include // the method symbols for the getter and setter, we don't want to generate them twice. var members = GetMembers(namedType).Where(s => s.Kind != SymbolKind.Property || PropertyGenerator.CanBeGenerated((IPropertySymbol)s)) .ToImmutableArray(); if (namedType.IsRecord) { declaration = GenerateRecordMembers(service, options, (RecordDeclarationSyntax)declaration, members, cancellationToken); } else { // If we're generating a ComImport type, then do not attempt to do any // reordering of members. if (namedType.IsComImport) options = options.With(autoInsertionLocation: false, sortMembers: false); if (options.GenerateMembers && namedType.TypeKind != TypeKind.Delegate) declaration = service.AddMembers(declaration, members, options, cancellationToken); } return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)); } private static RecordDeclarationSyntax GenerateRecordMembers( ICodeGenerationService service, CodeGenerationOptions options, RecordDeclarationSyntax recordDeclaration, ImmutableArray<ISymbol> members, CancellationToken cancellationToken) { if (!options.GenerateMembers) members = ImmutableArray<ISymbol>.Empty; // For a record, add record parameters if we have a primary constructor. var primaryConstructor = members.OfType<IMethodSymbol>().FirstOrDefault(m => CodeGenerationConstructorInfo.GetIsPrimaryConstructor(m)); if (primaryConstructor != null) { var parameterList = ParameterGenerator.GenerateParameterList(primaryConstructor.Parameters, isExplicit: false, options); recordDeclaration = recordDeclaration.WithParameterList(parameterList); // remove the primary constructor from the list of members to generate. members = members.Remove(primaryConstructor); // remove any fields/properties that were created by the primary constructor members = members.WhereAsArray(m => m is not IPropertySymbol and not IFieldSymbol || !primaryConstructor.Parameters.Any(p => p.Name == m.Name)); } // remove any implicit overrides to generate. members = members.WhereAsArray(m => !m.IsImplicitlyDeclared); // If there are no members, just make a simple record with no body if (members.Length == 0) return recordDeclaration.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); // Otherwise, give the record a body and add the members to it. recordDeclaration = recordDeclaration.WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) .WithSemicolonToken(default); return service.AddMembers(recordDeclaration, members, options, cancellationToken); } public static MemberDeclarationSyntax UpdateNamedTypeDeclaration( ICodeGenerationService service, MemberDeclarationSyntax declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(namedType, options); return reusableDeclarationSyntax == null ? GetDeclarationSyntaxWithoutMembersWorker(namedType, destination, options) : RemoveAllMembers(reusableDeclarationSyntax); } private static MemberDeclarationSyntax RemoveAllMembers(MemberDeclarationSyntax declaration) { switch (declaration.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)declaration).WithMembers(default); case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return ((TypeDeclarationSyntax)declaration).WithMembers(default); default: return declaration; } } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembersWorker( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { if (namedType.TypeKind == TypeKind.Enum) { return GenerateEnumDeclaration(namedType, destination, options); } else if (namedType.TypeKind == TypeKind.Delegate) { return GenerateDelegateDeclaration(namedType, destination, options); } TypeDeclarationSyntax typeDeclaration; if (namedType.IsRecord) { var isRecordClass = namedType.TypeKind is TypeKind.Class; var declarationKind = isRecordClass ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration; var classOrStructKeyword = SyntaxFactory.Token(isRecordClass ? default : SyntaxKind.StructKeyword); typeDeclaration = SyntaxFactory.RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, SyntaxFactory.Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), typeParameterList: null, parameterList: null, baseList: null, constraintClauses: default, openBraceToken: default, members: default, closeBraceToken: default, SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var kind = namedType.TypeKind == TypeKind.Struct ? SyntaxKind.StructDeclaration : namedType.TypeKind == TypeKind.Interface ? SyntaxKind.InterfaceDeclaration : SyntaxKind.ClassDeclaration; typeDeclaration = SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); } var result = typeDeclaration .WithAttributeLists(GenerateAttributeDeclarations(namedType, options)) .WithModifiers(GenerateModifiers(namedType, destination, options)) .WithTypeParameterList(GenerateTypeParameterList(namedType, options)) .WithBaseList(GenerateBaseList(namedType)) .WithConstraintClauses(GenerateConstraintClauses(namedType)); return result; } private static DelegateDeclarationSyntax GenerateDelegateDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var invokeMethod = namedType.DelegateInvokeMethod; Contract.ThrowIfNull(invokeMethod); return SyntaxFactory.DelegateDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), invokeMethod.ReturnType.GenerateTypeSyntax(), namedType.Name.ToIdentifierToken(), TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options), ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, isExplicit: false, options: options), namedType.TypeParameters.GenerateConstraintClauses()); } private static EnumDeclarationSyntax GenerateEnumDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32 ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax()))) : null; return SyntaxFactory.EnumDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), namedType.Name.ToIdentifierToken(), baseList: baseList, members: default); } private static SyntaxList<AttributeListSyntax> GenerateAttributeDeclarations( INamedTypeSymbol namedType, CodeGenerationOptions options) { return AttributeGenerator.GenerateAttributeLists(namedType.GetAttributes(), options); } private static SyntaxTokenList GenerateModifiers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); var defaultAccessibility = destination == CodeGenerationDestination.CompilationUnit || destination == CodeGenerationDestination.Namespace ? Accessibility.Internal : Accessibility.Private; AddAccessibilityModifiers(namedType.DeclaredAccessibility, tokens, options, defaultAccessibility); if (namedType.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } else { if (namedType.TypeKind == TypeKind.Class) { if (namedType.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (namedType.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } } } if (namedType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (namedType.IsRefLikeType) { tokens.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } private static TypeParameterListSyntax GenerateTypeParameterList( INamedTypeSymbol namedType, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options); } private static BaseListSyntax? GenerateBaseList(INamedTypeSymbol namedType) { var types = new List<BaseTypeSyntax>(); if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object) types.Add(SyntaxFactory.SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); foreach (var type in namedType.Interfaces) types.Add(SyntaxFactory.SimpleBaseType(type.GenerateTypeSyntax())); if (types.Count == 0) return null; return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(types)); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses(INamedTypeSymbol namedType) => namedType.TypeParameters.GenerateConstraintClauses(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamedTypeGenerator { public static TypeDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, TypeDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return AddMembersTo(destination, members); } public static BaseNamespaceDeclarationSyntax AddNamedTypeTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.Namespace, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return ConditionallyAddFormattingAnnotationTo( destination.WithMembers(members), members); } public static CompilationUnitSyntax AddNamedTypeTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamedTypeDeclaration(service, namedType, CodeGenerationDestination.CompilationUnit, options, cancellationToken); var members = Insert(destination.Members, declaration, options, availableIndices); return destination.WithMembers(members); } public static MemberDeclarationSyntax GenerateNamedTypeDeclaration( ICodeGenerationService service, INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; var declaration = GetDeclarationSyntaxWithoutMembers(namedType, destination, options); // If we are generating members then make sure to exclude properties that cannot be generated. // Reason: Calling AddProperty on a propertysymbol that can't be generated (like one with params) causes // the getter and setter to get generated instead. Since the list of members is going to include // the method symbols for the getter and setter, we don't want to generate them twice. var members = GetMembers(namedType).Where(s => s.Kind != SymbolKind.Property || PropertyGenerator.CanBeGenerated((IPropertySymbol)s)) .ToImmutableArray(); if (namedType.IsRecord) { declaration = GenerateRecordMembers(service, options, (RecordDeclarationSyntax)declaration, members, cancellationToken); } else { // If we're generating a ComImport type, then do not attempt to do any // reordering of members. if (namedType.IsComImport) options = options.With(autoInsertionLocation: false, sortMembers: false); if (options.GenerateMembers && namedType.TypeKind != TypeKind.Delegate) declaration = service.AddMembers(declaration, members, options, cancellationToken); } return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)); } private static RecordDeclarationSyntax GenerateRecordMembers( ICodeGenerationService service, CodeGenerationOptions options, RecordDeclarationSyntax recordDeclaration, ImmutableArray<ISymbol> members, CancellationToken cancellationToken) { if (!options.GenerateMembers) members = ImmutableArray<ISymbol>.Empty; // For a record, add record parameters if we have a primary constructor. var primaryConstructor = members.OfType<IMethodSymbol>().FirstOrDefault(m => CodeGenerationConstructorInfo.GetIsPrimaryConstructor(m)); if (primaryConstructor != null) { var parameterList = ParameterGenerator.GenerateParameterList(primaryConstructor.Parameters, isExplicit: false, options); recordDeclaration = recordDeclaration.WithParameterList(parameterList); // remove the primary constructor from the list of members to generate. members = members.Remove(primaryConstructor); // remove any fields/properties that were created by the primary constructor members = members.WhereAsArray(m => m is not IPropertySymbol and not IFieldSymbol || !primaryConstructor.Parameters.Any(p => p.Name == m.Name)); } // remove any implicit overrides to generate. members = members.WhereAsArray(m => !m.IsImplicitlyDeclared); // If there are no members, just make a simple record with no body if (members.Length == 0) return recordDeclaration.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); // Otherwise, give the record a body and add the members to it. recordDeclaration = recordDeclaration.WithOpenBraceToken(SyntaxFactory.Token(SyntaxKind.OpenBraceToken)) .WithCloseBraceToken(SyntaxFactory.Token(SyntaxKind.CloseBraceToken)) .WithSemicolonToken(default); return service.AddMembers(recordDeclaration, members, options, cancellationToken); } public static MemberDeclarationSyntax UpdateNamedTypeDeclaration( ICodeGenerationService service, MemberDeclarationSyntax declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol<MemberDeclarationSyntax>(namedType, options); return reusableDeclarationSyntax == null ? GetDeclarationSyntaxWithoutMembersWorker(namedType, destination, options) : RemoveAllMembers(reusableDeclarationSyntax); } private static MemberDeclarationSyntax RemoveAllMembers(MemberDeclarationSyntax declaration) { switch (declaration.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)declaration).WithMembers(default); case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return ((TypeDeclarationSyntax)declaration).WithMembers(default); default: return declaration; } } private static MemberDeclarationSyntax GetDeclarationSyntaxWithoutMembersWorker( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { if (namedType.TypeKind == TypeKind.Enum) { return GenerateEnumDeclaration(namedType, destination, options); } else if (namedType.TypeKind == TypeKind.Delegate) { return GenerateDelegateDeclaration(namedType, destination, options); } TypeDeclarationSyntax typeDeclaration; if (namedType.IsRecord) { var isRecordClass = namedType.TypeKind is TypeKind.Class; var declarationKind = isRecordClass ? SyntaxKind.RecordDeclaration : SyntaxKind.RecordStructDeclaration; var classOrStructKeyword = SyntaxFactory.Token(isRecordClass ? default : SyntaxKind.StructKeyword); typeDeclaration = SyntaxFactory.RecordDeclaration(kind: declarationKind, attributeLists: default, modifiers: default, SyntaxFactory.Token(SyntaxKind.RecordKeyword), classOrStructKeyword, namedType.Name.ToIdentifierToken(), typeParameterList: null, parameterList: null, baseList: null, constraintClauses: default, openBraceToken: default, members: default, closeBraceToken: default, SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } else { var kind = namedType.TypeKind == TypeKind.Struct ? SyntaxKind.StructDeclaration : namedType.TypeKind == TypeKind.Interface ? SyntaxKind.InterfaceDeclaration : SyntaxKind.ClassDeclaration; typeDeclaration = SyntaxFactory.TypeDeclaration(kind, namedType.Name.ToIdentifierToken()); } var result = typeDeclaration .WithAttributeLists(GenerateAttributeDeclarations(namedType, options)) .WithModifiers(GenerateModifiers(namedType, destination, options)) .WithTypeParameterList(GenerateTypeParameterList(namedType, options)) .WithBaseList(GenerateBaseList(namedType)) .WithConstraintClauses(GenerateConstraintClauses(namedType)); return result; } private static DelegateDeclarationSyntax GenerateDelegateDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var invokeMethod = namedType.DelegateInvokeMethod; Contract.ThrowIfNull(invokeMethod); return SyntaxFactory.DelegateDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), invokeMethod.ReturnType.GenerateTypeSyntax(), namedType.Name.ToIdentifierToken(), TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options), ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, isExplicit: false, options: options), namedType.TypeParameters.GenerateConstraintClauses()); } private static EnumDeclarationSyntax GenerateEnumDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var baseList = namedType.EnumUnderlyingType != null && namedType.EnumUnderlyingType.SpecialType != SpecialType.System_Int32 ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType(namedType.EnumUnderlyingType.GenerateTypeSyntax()))) : null; return SyntaxFactory.EnumDeclaration( GenerateAttributeDeclarations(namedType, options), GenerateModifiers(namedType, destination, options), namedType.Name.ToIdentifierToken(), baseList: baseList, members: default); } private static SyntaxList<AttributeListSyntax> GenerateAttributeDeclarations( INamedTypeSymbol namedType, CodeGenerationOptions options) { return AttributeGenerator.GenerateAttributeLists(namedType.GetAttributes(), options); } private static SyntaxTokenList GenerateModifiers( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options) { var tokens = ArrayBuilder<SyntaxToken>.GetInstance(); var defaultAccessibility = destination == CodeGenerationDestination.CompilationUnit || destination == CodeGenerationDestination.Namespace ? Accessibility.Internal : Accessibility.Private; AddAccessibilityModifiers(namedType.DeclaredAccessibility, tokens, options, defaultAccessibility); if (namedType.IsStatic) { tokens.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } else { if (namedType.TypeKind == TypeKind.Class) { if (namedType.IsAbstract) { tokens.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); } if (namedType.IsSealed) { tokens.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); } } } if (namedType.IsReadOnly) { tokens.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); } if (namedType.IsRefLikeType) { tokens.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); } return tokens.ToSyntaxTokenListAndFree(); } private static TypeParameterListSyntax GenerateTypeParameterList( INamedTypeSymbol namedType, CodeGenerationOptions options) { return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters, options); } private static BaseListSyntax? GenerateBaseList(INamedTypeSymbol namedType) { var types = new List<BaseTypeSyntax>(); if (namedType.TypeKind == TypeKind.Class && namedType.BaseType != null && namedType.BaseType.SpecialType != Microsoft.CodeAnalysis.SpecialType.System_Object) types.Add(SyntaxFactory.SimpleBaseType(namedType.BaseType.GenerateTypeSyntax())); foreach (var type in namedType.Interfaces) types.Add(SyntaxFactory.SimpleBaseType(type.GenerateTypeSyntax())); if (types.Count == 0) return null; return SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(types)); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GenerateConstraintClauses(INamedTypeSymbol namedType) => namedType.TypeParameters.GenerateConstraintClauses(); } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (!(declaration is NamespaceDeclarationSyntax)) { throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); } var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.CompilationUnit => ((CompilationUnitSyntax)declaration).WithMembers(default), SyntaxKind.NamespaceDeclaration => ((NamespaceDeclarationSyntax)declaration).WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (!(declaration is NamespaceDeclarationSyntax)) { throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); } var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.CompilationUnit => ((CompilationUnitSyntax)declaration).WithMembers(default), SyntaxKind.NamespaceDeclaration => ((NamespaceDeclarationSyntax)declaration).WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/AbstractCSharpSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Simplification.Simplifiers; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { /// <summary> /// Contains helpers used by several simplifier subclasses. /// </summary> internal abstract class AbstractCSharpSimplifier<TSyntax, TSimplifiedSyntax> : AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { /// <summary> /// Returns the predefined keyword kind for a given <see cref="SpecialType"/>. /// </summary> /// <param name="specialType">The <see cref="SpecialType"/> of this type.</param> /// <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns> protected static SyntaxKind GetPredefinedKeywordKind(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxKind.BoolKeyword, SpecialType.System_Byte => SyntaxKind.ByteKeyword, SpecialType.System_SByte => SyntaxKind.SByteKeyword, SpecialType.System_Int32 => SyntaxKind.IntKeyword, SpecialType.System_UInt32 => SyntaxKind.UIntKeyword, SpecialType.System_Int16 => SyntaxKind.ShortKeyword, SpecialType.System_UInt16 => SyntaxKind.UShortKeyword, SpecialType.System_Int64 => SyntaxKind.LongKeyword, SpecialType.System_UInt64 => SyntaxKind.ULongKeyword, SpecialType.System_Single => SyntaxKind.FloatKeyword, SpecialType.System_Double => SyntaxKind.DoubleKeyword, SpecialType.System_Decimal => SyntaxKind.DecimalKeyword, SpecialType.System_String => SyntaxKind.StringKeyword, SpecialType.System_Char => SyntaxKind.CharKeyword, SpecialType.System_Object => SyntaxKind.ObjectKeyword, SpecialType.System_Void => SyntaxKind.VoidKeyword, _ => SyntaxKind.None, }; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Most trees do not have using alias directives, so avoid the expensive " + nameof(CSharpExtensions.GetSymbolInfo) + " call for this case.")] protected static bool TryReplaceExpressionWithAlias( ExpressionSyntax node, SemanticModel semanticModel, ISymbol symbol, CancellationToken cancellationToken, out IAliasSymbol aliasReplacement) { aliasReplacement = null; if (!IsAliasReplaceableExpression(node)) return false; // Avoid the TryReplaceWithAlias algorithm if the tree has no using alias directives. Since the input node // might be a speculative node (not fully rooted in a tree), we use the original semantic model to find the // equivalent node in the original tree, and from there determine if the tree has any using alias // directives. var originalModel = semanticModel.GetOriginalSemanticModel(); // Perf: We are only using the syntax tree root in a fast-path syntax check. If the root is not readily // available, it is fine to continue through the normal algorithm. if (originalModel.SyntaxTree.TryGetRoot(out var root)) { if (!HasUsingAliasDirective(root)) { return false; } } // If the Symbol is a constructor get its containing type if (symbol.IsConstructor()) { symbol = symbol.ContainingType; } if (node is QualifiedNameSyntax || node is AliasQualifiedNameSyntax) { SyntaxAnnotation aliasAnnotationInfo = null; // The following condition checks if the user has used alias in the original code and // if so the expression is replaced with the Alias if (node is QualifiedNameSyntax qualifiedNameNode) { if (qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameNode) { if (aliasQualifiedNameNode.Name.Identifier.HasAnnotations(AliasAnnotation.Kind)) { aliasAnnotationInfo = aliasQualifiedNameNode.Name.Identifier.GetAnnotations(AliasAnnotation.Kind).Single(); } } if (aliasAnnotationInfo != null) { var aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo); var aliasIdentifier = SyntaxFactory.IdentifierName(aliasName); var aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace); if (aliasTypeInfo != null) { aliasReplacement = aliasTypeInfo; return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } } } if (node.Kind() == SyntaxKind.IdentifierName && semanticModel.GetAliasInfo((IdentifierNameSyntax)node, cancellationToken) != null) { return false; } // an alias can only replace a type or namespace if (symbol == null || (symbol.Kind != SymbolKind.Namespace && symbol.Kind != SymbolKind.NamedType)) { return false; } var preferAliasToQualifiedName = true; if (node is QualifiedNameSyntax qualifiedName) { if (!qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } if (node is AliasQualifiedNameSyntax aliasQualifiedNameSyntax) { if (!aliasQualifiedNameSyntax.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { var type = semanticModel.GetTypeInfo(node, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None) { preferAliasToQualifiedName = false; } } } } aliasReplacement = GetAliasForSymbol((INamespaceOrTypeSymbol)symbol, node.GetFirstToken(), semanticModel, cancellationToken); if (aliasReplacement != null && preferAliasToQualifiedName) { return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol); } return false; } private static bool IsAliasReplaceableExpression(ExpressionSyntax expression) { var current = expression; while (current.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax currentMember)) { current = currentMember.Expression; continue; } return current.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.IdentifierName, SyntaxKind.GenericName, SyntaxKind.QualifiedName); } private static bool HasUsingAliasDirective(SyntaxNode syntax) { var (usings, members) = syntax switch { BaseNamespaceDeclarationSyntax ns => (ns.Usings, ns.Members), CompilationUnitSyntax compilationUnit => (compilationUnit.Usings, compilationUnit.Members), _ => default, }; foreach (var usingDirective in usings) { if (usingDirective.Alias != null) return true; } foreach (var member in members) { if (HasUsingAliasDirective(member)) return true; } return false; } // We must verify that the alias actually binds back to the thing it's aliasing. // It's possible there's another symbol with the same name as the alias that binds // first private static bool ValidateAliasForTarget(IAliasSymbol aliasReplacement, SemanticModel semanticModel, ExpressionSyntax node, ISymbol symbol) { var aliasName = aliasReplacement.Name; // If we're the argument of a nameof(X.Y) call, then we can't simplify to an // alias unless the alias has the same name as us (i.e. 'Y'). if (node.IsNameOfArgumentExpression()) { var nameofValueOpt = semanticModel.GetConstantValue(node.Parent.Parent.Parent); if (!nameofValueOpt.HasValue) { return false; } if (nameofValueOpt.Value is string existingVal && existingVal != aliasName) { return false; } } var boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name: aliasName); if (boundSymbols.Length == 1) { if (boundSymbols[0] is IAliasSymbol && aliasReplacement.Target.Equals(symbol)) { return true; } } return false; } private static IAliasSymbol GetAliasForSymbol(INamespaceOrTypeSymbol symbol, SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken) { var originalSemanticModel = semanticModel.GetOriginalSemanticModel(); if (!originalSemanticModel.SyntaxTree.HasCompilationUnitRoot) { return null; } var namespaceId = GetNamespaceIdForAliasSearch(semanticModel, token, cancellationToken); if (namespaceId < 0) { return null; } if (!AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out var aliasSymbol)) { // add cache AliasSymbolCache.AddAliasSymbols(originalSemanticModel, namespaceId, semanticModel.LookupNamespacesAndTypes(token.SpanStart).OfType<IAliasSymbol>()); // retry AliasSymbolCache.TryGetAliasSymbol(originalSemanticModel, namespaceId, symbol, out aliasSymbol); } return aliasSymbol; } private static int GetNamespaceIdForAliasSearch(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var startNode = GetStartNodeForNamespaceId(semanticModel, token, cancellationToken); if (!startNode.SyntaxTree.HasCompilationUnitRoot) { return -1; } // NOTE: If we're currently in a block of usings, then we want to collect the // aliases that are higher up than this block. Using aliases declared in a block of // usings are not usable from within that same block. var usingDirective = startNode.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null) { startNode = usingDirective.Parent.Parent; if (startNode == null) { return -1; } } // check whether I am under a namespace var @namespace = startNode.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); if (@namespace != null) { // since we have node inside of the root, root should be already there // search for namespace id should be quite cheap since normally there should be // only a few namespace defined in a source file if it is not 1. that is why it is // not cached. var startIndex = 1; return GetNamespaceId(startNode.SyntaxTree.GetRoot(cancellationToken), @namespace, ref startIndex); } // no namespace, under compilation unit directly return 0; } private static SyntaxNode GetStartNodeForNamespaceId(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { if (!semanticModel.IsSpeculativeSemanticModel) { return token.Parent; } var originalSemanticMode = semanticModel.GetOriginalSemanticModel(); token = originalSemanticMode.SyntaxTree.GetRoot(cancellationToken).FindToken(semanticModel.OriginalPositionForSpeculation); return token.Parent; } private static int GetNamespaceId(SyntaxNode container, BaseNamespaceDeclarationSyntax target, ref int index) => container switch { CompilationUnitSyntax compilation => GetNamespaceId(compilation.Members, target, ref index), BaseNamespaceDeclarationSyntax @namespace => GetNamespaceId(@namespace.Members, target, ref index), _ => throw ExceptionUtilities.UnexpectedValue(container) }; private static int GetNamespaceId(SyntaxList<MemberDeclarationSyntax> members, BaseNamespaceDeclarationSyntax target, ref int index) { foreach (var member in members) { if (member is not BaseNamespaceDeclarationSyntax childNamespace) continue; if (childNamespace == target) return index; index++; var result = GetNamespaceId(childNamespace, target, ref index); if (result > 0) return result; } return -1; } protected static TypeSyntax CreatePredefinedTypeSyntax(ExpressionSyntax expression, SyntaxKind keywordKind) => SyntaxFactory.PredefinedType(SyntaxFactory.Token(expression.GetLeadingTrivia(), keywordKind, expression.GetTrailingTrivia())); protected static bool InsideNameOfExpression(ExpressionSyntax expression, SemanticModel semanticModel) { var nameOfInvocationExpr = expression.FirstAncestorOrSelf<InvocationExpressionSyntax>( invocationExpr => { return invocationExpr.Expression is IdentifierNameSyntax identifierName && identifierName.Identifier.Text == "nameof" && semanticModel.GetConstantValue(invocationExpr).HasValue && semanticModel.GetTypeInfo(invocationExpr).Type.SpecialType == SpecialType.System_String; }); return nameOfInvocationExpr != null; } protected static bool PreferPredefinedTypeKeywordInMemberAccess(ExpressionSyntax expression, OptionSet optionSet, SemanticModel semanticModel) { if (!SimplificationHelpers.PreferPredefinedTypeKeywordInMemberAccess(optionSet, semanticModel.Language)) return false; return (expression.IsDirectChildOfMemberAccessExpression() || expression.InsideCrefReference()) && !InsideNameOfExpression(expression, semanticModel); } protected static bool WillConflictWithExistingLocal( ExpressionSyntax expression, ExpressionSyntax simplifiedNode, SemanticModel semanticModel) { if (simplifiedNode is IdentifierNameSyntax identifierName && !SyntaxFacts.IsInNamespaceOrTypeContext(expression)) { var symbols = semanticModel.LookupSymbols(expression.SpanStart, name: identifierName.Identifier.ValueText); return symbols.Any(s => s is ILocalSymbol); } return false; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { using Microsoft.CodeAnalysis.Rename.ConflictEngine; internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax> { public static readonly NameSimplifier Instance = new(); private NameSimplifier() { } public override bool TrySimplify( NameSyntax name, SemanticModel semanticModel, OptionSet optionSet, out TypeSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken) { replacementNode = null; issueSpan = default; if (name.IsVar) { return false; } // we should not simplify a name of a namespace declaration if (IsPartOfNamespaceDeclarationName(name)) { return false; } // We can simplify Qualified names and AliasQualifiedNames. Generally, if we have // something like "A.B.C.D", we only consider the full thing something we can simplify. // However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the // first open name. This is because if we remove the open name, we'll often change // meaning as "D" will bind to C<T>.D which is different than C<>.D! if (name is QualifiedNameSyntax qualifiedName) { var left = qualifiedName.Left; if (ContainsOpenName(left)) { // Don't simplify A.B<>.C return false; } } // 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and // nothing we can do here. var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name); if (symbol == null) { return false; } // treat constructor names as types var method = symbol as IMethodSymbol; if (method.IsConstructor()) { symbol = method.ContainingType; } if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName) { var genericName = (GenericNameSyntax)name; replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier) .WithLeadingTrivia(genericName.GetLeadingTrivia()) .WithTrailingTrivia(genericName.GetTrailingTrivia()); issueSpan = genericName.TypeArgumentList.Span; return CanReplaceWithReducedName( name, replacementNode, semanticModel, cancellationToken); } if (!(symbol is INamespaceOrTypeSymbol)) { return false; } if (name.HasAnnotations(SpecialTypeAnnotation.Kind)) { replacementNode = SyntaxFactory.PredefinedType( SyntaxFactory.Token( name.GetLeadingTrivia(), GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())), name.GetTrailingTrivia())); issueSpan = name.Span; return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel); } else { if (!name.IsRightSideOfDotOrColonColon()) { if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement)) { // get the token text as it appears in source code to preserve e.g. Unicode character escaping var text = aliasReplacement.Name; var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault(); if (syntaxRef != null) { var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier; text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString(); } var identifierToken = SyntaxFactory.Identifier( name.GetLeadingTrivia(), SyntaxKind.IdentifierToken, text, aliasReplacement.Name, name.GetTrailingTrivia()); identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name); replacementNode = SyntaxFactory.IdentifierName(identifierToken); // Merge annotation to new syntax node var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind); foreach (var annotatedNodeOrToken in annotatedNodesOrTokens) { if (annotatedNodeOrToken.IsToken) { identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken); } else { replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode); } } annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind); foreach (var annotatedNodeOrToken in annotatedNodesOrTokens) { if (annotatedNodeOrToken.IsToken) { identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken); } else { replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode); } } replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken); issueSpan = name.Span; // In case the alias name is the same as the last name of the alias target, we only include // the left part of the name in the unnecessary span to Not confuse uses. if (name.Kind() == SyntaxKind.QualifiedName) { var qualifiedName3 = (QualifiedNameSyntax)name; if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText) { issueSpan = qualifiedName3.Left.Span; } } // first check if this would be a valid reduction if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel)) { // in case this alias name ends with "Attribute", we're going to see if we can also // remove that suffix. if (TryReduceAttributeSuffix( name, identifierToken, out var replacementNodeWithoutAttributeSuffix, out var issueSpanWithoutAttributeSuffix)) { if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken)) { replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix); issueSpan = issueSpanWithoutAttributeSuffix; } } return true; } return false; } var nameHasNoAlias = false; if (name is SimpleNameSyntax simpleName) { if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind)) { nameHasNoAlias = true; } } if (name is QualifiedNameSyntax qualifiedName2) { if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { nameHasNoAlias = true; } } if (name is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Name is SimpleNameSyntax && !aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) && !aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { nameHasNoAlias = true; } } var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken); if (nameHasNoAlias && aliasInfo == null) { // Don't simplify to predefined type if name is part of a QualifiedName. // QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can). // In other words, the left side of a QualifiedName can't be a PredefinedTypeName. var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel); var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel); if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext)) { // See if we can simplify this name (like System.Int32) to a built-in type (like 'int'). // If not, we'll still fall through and see if we can convert it to Int32. var codeStyleOptionName = inDeclarationContext ? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration) : nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); var type = semanticModel.GetTypeInfo(name, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None && CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName)) { return true; } } else { var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol; if (typeSymbol.IsKind(SymbolKind.NamedType)) { var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType); if (keywordKind != SyntaxKind.None && CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName)) { return true; } } } } } // Nullable rewrite: Nullable<int> -> int? // Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName()) { var type = (INamedTypeSymbol)symbol; if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel)) { GenericNameSyntax genericName; if (name.Kind() == SyntaxKind.QualifiedName) { genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right; } else { genericName = (GenericNameSyntax)name; } var oldType = genericName.TypeArgumentList.Arguments.First(); if (oldType.Kind() == SyntaxKind.OmittedTypeArgument) { return false; } replacementNode = SyntaxFactory.NullableType(oldType) .WithLeadingTrivia(name.GetLeadingTrivia()) .WithTrailingTrivia(name.GetTrailingTrivia()); issueSpan = name.Span; // we need to simplify the whole qualified name at once, because replacing the identifier on the left in // System.Nullable<int> alone would be illegal. // If this fails we want to continue to try at least to remove the System if possible. if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel)) { return true; } } } } SyntaxToken identifier; switch (name.Kind()) { case SyntaxKind.AliasQualifiedName: var simpleName = ((AliasQualifiedNameSyntax)name).Name .WithLeadingTrivia(name.GetLeadingTrivia()); simpleName = simpleName.ReplaceToken(simpleName.Identifier, ((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo( simpleName.Identifier.WithLeadingTrivia( ((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia))); replacementNode = simpleName; issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span; break; case SyntaxKind.QualifiedName: replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia()); issueSpan = ((QualifiedNameSyntax)name).Left.Span; break; case SyntaxKind.IdentifierName: identifier = ((IdentifierNameSyntax)name).Identifier; // we can try to remove the Attribute suffix if this is the attribute name TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan); break; } } if (replacementNode == null) { return false; } // We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in // order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if // it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell // if we can reduce by looking by also looking at what comes next to see if it will // cause the simplified name to bind to the instance or static side. if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken)) { return true; } return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken); } private static bool TryReduceCrefColorColor( NameSyntax name, TypeSyntax replacement, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!name.InsideCrefReference()) return false; if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name) { // we have <see cref="A.B.C.D"/> and we're trying to see if we can replace // A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a // QualifiedCrefSyntax var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member); if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken)) return true; } else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name && replacement is NameSyntax replacementName) { // we have <see cref="A.B.C.D"/> and we're trying to see if we can replace // A.B with B. In this case the parent of A.B is A.B.C which is a // QualifiedNameSyntax var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right); return CanReplaceWithReducedName( qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken); } return false; } private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel) { if (!type.IsNullable()) { return false; } if (type.IsUnboundGenericType) { // Don't simplify unbound generic type "Nullable<>". return false; } if (InsideNameOfExpression(name, semanticModel)) { // Nullable<T> can't be simplified to T? in nameof expressions. return false; } if (!name.InsideCrefReference()) { // Nullable<T> can always be simplified to T? outside crefs. return true; } if (name.Parent is NameMemberCrefSyntax) return false; // Inside crefs, if the T in this Nullable{T} is being declared right here // then this Nullable{T} is not a constructed generic type and we should // not offer to simplify this to T?. // // For example, we should not offer the simplification in the following cases where // T does not bind to an existing type / type parameter in the user's code. // - <see cref="Nullable{T}"/> // - <see cref="System.Nullable{T}.Value"/> // // And we should offer the simplification in the following cases where SomeType and // SomeMethod bind to a type and method declared elsewhere in the users code. // - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/> var argument = type.TypeArguments.SingleOrDefault(); if (argument == null || argument.IsErrorType()) { return false; } var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault(); if (argumentDecl == null) { // The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)). return true; } return !name.Span.Contains(argumentDecl.Span); } private static bool CanReplaceWithPredefinedTypeKeywordInContext( NameSyntax name, SemanticModel semanticModel, out TypeSyntax replacementNode, ref TextSpan issueSpan, SyntaxKind keywordKind, string codeStyleOptionName) { replacementNode = CreatePredefinedTypeSyntax(name, keywordKind); issueSpan = name.Span; // we want to show the whole name expression as unnecessary var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel); if (canReduce) { replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName)); } return canReduce; } private static bool TryReduceAttributeSuffix( NameSyntax name, SyntaxToken identifierToken, out TypeSyntax replacementNode, out TextSpan issueSpan) { issueSpan = default; replacementNode = null; // we can try to remove the Attribute suffix if this is the attribute name if (SyntaxFacts.IsAttributeName(name)) { if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon()) { const string AttributeName = "Attribute"; // an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation)) { // weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code. // so we need another check for keywords manually. var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9); if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None) { return false; } // if this attribute name in source contained Unicode escaping, we will loose it now // because there is no easy way to determine the substring from identifier->ToString() // which would be needed to pass to SyntaxFactory.Identifier // The result is an unescaped Unicode character in source. // once we remove the Attribute suffix, we can't use an escaped identifier var newIdentifierToken = identifierToken.CopyAnnotationsTo( SyntaxFactory.Identifier( identifierToken.LeadingTrivia, newAttributeName, identifierToken.TrailingTrivia)); replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken) .WithLeadingTrivia(name.GetLeadingTrivia()); issueSpan = new TextSpan(identifierToken.Span.End - 9, 9); return true; } } } return false; } /// <summary> /// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax /// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name /// property. /// </summary> /// <param name="node"></param> /// <returns></returns> private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node) { var parent = node; while (parent != null) { switch (parent.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: node = parent; parent = parent.Parent; break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent; return object.Equals(namespaceDeclaration.Name, node); default: return false; } } return false; } public static bool CanReplaceWithReducedNameInContext( NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel) { // Check for certain things that would prevent us from reducing this name in this context. // For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply // not allowed in the C# grammar. if (IsNonNameSyntaxInUsingDirective(name, reducedName) || WillConflictWithExistingLocal(name, reducedName, semanticModel) || IsAmbiguousCast(name, reducedName) || IsNullableTypeInPointerExpression(reducedName) || IsNotNullableReplaceable(name, reducedName) || IsNonReducableQualifiedNameInUsingDirective(semanticModel, name)) { return false; } return true; } private static bool ContainsOpenName(NameSyntax name) { if (name is QualifiedNameSyntax qualifiedName) { return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right); } else if (name is GenericNameSyntax genericName) { return genericName.IsUnboundGenericName; } else { return false; } } private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken) { var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken); if (speculationAnalyzer.ReplacementChangesSemantics()) { return false; } return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel); } private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName) { if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType)) { if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument) return true; return name.IsLeftSideOfDot() || name.IsRightSideOfDot(); } return false; } private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode) { // Note: nullable type syntax is not allowed in pointer type syntax if (simplifiedNode.Kind() == SyntaxKind.NullableType && simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax)) { return true; } return false; } private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { return expression.IsParentKind(SyntaxKind.UsingDirective) && !(simplifiedNode is NameSyntax); } private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { // Can't simplify a type name in a cast expression if it would then cause the cast to be // parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to // (Bar)+1 then that's an arithmetic expression. if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Type == expression) { var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode); var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString()); if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression)) { return true; } } return false; } private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name) { // Whereas most of the time we do not want to reduce namespace names, We will // make an exception for namespaces with the global:: alias. return IsQualifiedNameInUsingDirective(model, name) && !IsGlobalAliasQualifiedName(name); } private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name) { while (name.IsLeftSideOfQualifiedName()) { name = (NameSyntax)name.Parent; } if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) && usingDirective.Alias == null) { // We're a qualified name in a using. We don't want to reduce this name as people like // fully qualified names in usings so they can properly tell what the name is resolving // to. // However, if this name is actually referencing the special Script class, then we do // want to allow that to be reduced. return !IsInScriptClass(model, name); } return false; } private static bool IsGlobalAliasQualifiedName(NameSyntax name) { // Checks whether the `global::` alias is applied to the name return name is AliasQualifiedNameSyntax aliasName && aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword); } private static bool IsInScriptClass(SemanticModel model, NameSyntax name) { var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol; while (symbol != null) { if (symbol.IsScriptClass) { return true; } symbol = symbol.ContainingType; } return false; } private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel) { return !name.IsDirectChildOfMemberAccessExpression() && !name.InsideCrefReference() && !InsideNameOfExpression(name, semanticModel) && SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers { using Microsoft.CodeAnalysis.Rename.ConflictEngine; internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax> { public static readonly NameSimplifier Instance = new(); private NameSimplifier() { } public override bool TrySimplify( NameSyntax name, SemanticModel semanticModel, OptionSet optionSet, out TypeSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken) { replacementNode = null; issueSpan = default; if (name.IsVar) { return false; } // we should not simplify a name of a namespace declaration if (IsPartOfNamespaceDeclarationName(name)) { return false; } // We can simplify Qualified names and AliasQualifiedNames. Generally, if we have // something like "A.B.C.D", we only consider the full thing something we can simplify. // However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the // first open name. This is because if we remove the open name, we'll often change // meaning as "D" will bind to C<T>.D which is different than C<>.D! if (name is QualifiedNameSyntax qualifiedName) { var left = qualifiedName.Left; if (ContainsOpenName(left)) { // Don't simplify A.B<>.C return false; } } // 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and // nothing we can do here. var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name); if (symbol == null) { return false; } // treat constructor names as types var method = symbol as IMethodSymbol; if (method.IsConstructor()) { symbol = method.ContainingType; } if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName) { var genericName = (GenericNameSyntax)name; replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier) .WithLeadingTrivia(genericName.GetLeadingTrivia()) .WithTrailingTrivia(genericName.GetTrailingTrivia()); issueSpan = genericName.TypeArgumentList.Span; return CanReplaceWithReducedName( name, replacementNode, semanticModel, cancellationToken); } if (!(symbol is INamespaceOrTypeSymbol)) { return false; } if (name.HasAnnotations(SpecialTypeAnnotation.Kind)) { replacementNode = SyntaxFactory.PredefinedType( SyntaxFactory.Token( name.GetLeadingTrivia(), GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())), name.GetTrailingTrivia())); issueSpan = name.Span; return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel); } else { if (!name.IsRightSideOfDotOrColonColon()) { if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement)) { // get the token text as it appears in source code to preserve e.g. Unicode character escaping var text = aliasReplacement.Name; var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault(); if (syntaxRef != null) { var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier; text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString(); } var identifierToken = SyntaxFactory.Identifier( name.GetLeadingTrivia(), SyntaxKind.IdentifierToken, text, aliasReplacement.Name, name.GetTrailingTrivia()); identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name); replacementNode = SyntaxFactory.IdentifierName(identifierToken); // Merge annotation to new syntax node var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind); foreach (var annotatedNodeOrToken in annotatedNodesOrTokens) { if (annotatedNodeOrToken.IsToken) { identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken); } else { replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode); } } annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind); foreach (var annotatedNodeOrToken in annotatedNodesOrTokens) { if (annotatedNodeOrToken.IsToken) { identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken); } else { replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode); } } replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken); issueSpan = name.Span; // In case the alias name is the same as the last name of the alias target, we only include // the left part of the name in the unnecessary span to Not confuse uses. if (name.Kind() == SyntaxKind.QualifiedName) { var qualifiedName3 = (QualifiedNameSyntax)name; if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText) { issueSpan = qualifiedName3.Left.Span; } } // first check if this would be a valid reduction if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel)) { // in case this alias name ends with "Attribute", we're going to see if we can also // remove that suffix. if (TryReduceAttributeSuffix( name, identifierToken, out var replacementNodeWithoutAttributeSuffix, out var issueSpanWithoutAttributeSuffix)) { if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken)) { replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix); issueSpan = issueSpanWithoutAttributeSuffix; } } return true; } return false; } var nameHasNoAlias = false; if (name is SimpleNameSyntax simpleName) { if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind)) { nameHasNoAlias = true; } } if (name is QualifiedNameSyntax qualifiedName2) { if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { nameHasNoAlias = true; } } if (name is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Name is SimpleNameSyntax && !aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) && !aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation)) { nameHasNoAlias = true; } } var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken); if (nameHasNoAlias && aliasInfo == null) { // Don't simplify to predefined type if name is part of a QualifiedName. // QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can). // In other words, the left side of a QualifiedName can't be a PredefinedTypeName. var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel); var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel); if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext)) { // See if we can simplify this name (like System.Int32) to a built-in type (like 'int'). // If not, we'll still fall through and see if we can convert it to Int32. var codeStyleOptionName = inDeclarationContext ? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration) : nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess); var type = semanticModel.GetTypeInfo(name, cancellationToken).Type; if (type != null) { var keywordKind = GetPredefinedKeywordKind(type.SpecialType); if (keywordKind != SyntaxKind.None && CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName)) { return true; } } else { var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol; if (typeSymbol.IsKind(SymbolKind.NamedType)) { var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType); if (keywordKind != SyntaxKind.None && CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName)) { return true; } } } } } // Nullable rewrite: Nullable<int> -> int? // Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName()) { var type = (INamedTypeSymbol)symbol; if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel)) { GenericNameSyntax genericName; if (name.Kind() == SyntaxKind.QualifiedName) { genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right; } else { genericName = (GenericNameSyntax)name; } var oldType = genericName.TypeArgumentList.Arguments.First(); if (oldType.Kind() == SyntaxKind.OmittedTypeArgument) { return false; } replacementNode = SyntaxFactory.NullableType(oldType) .WithLeadingTrivia(name.GetLeadingTrivia()) .WithTrailingTrivia(name.GetTrailingTrivia()); issueSpan = name.Span; // we need to simplify the whole qualified name at once, because replacing the identifier on the left in // System.Nullable<int> alone would be illegal. // If this fails we want to continue to try at least to remove the System if possible. if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel)) { return true; } } } } SyntaxToken identifier; switch (name.Kind()) { case SyntaxKind.AliasQualifiedName: var simpleName = ((AliasQualifiedNameSyntax)name).Name .WithLeadingTrivia(name.GetLeadingTrivia()); simpleName = simpleName.ReplaceToken(simpleName.Identifier, ((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo( simpleName.Identifier.WithLeadingTrivia( ((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia))); replacementNode = simpleName; issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span; break; case SyntaxKind.QualifiedName: replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia()); issueSpan = ((QualifiedNameSyntax)name).Left.Span; break; case SyntaxKind.IdentifierName: identifier = ((IdentifierNameSyntax)name).Identifier; // we can try to remove the Attribute suffix if this is the attribute name TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan); break; } } if (replacementNode == null) { return false; } // We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in // order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if // it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell // if we can reduce by looking by also looking at what comes next to see if it will // cause the simplified name to bind to the instance or static side. if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken)) { return true; } return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken); } private static bool TryReduceCrefColorColor( NameSyntax name, TypeSyntax replacement, SemanticModel semanticModel, CancellationToken cancellationToken) { if (!name.InsideCrefReference()) return false; if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name) { // we have <see cref="A.B.C.D"/> and we're trying to see if we can replace // A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a // QualifiedCrefSyntax var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member); if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken)) return true; } else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name && replacement is NameSyntax replacementName) { // we have <see cref="A.B.C.D"/> and we're trying to see if we can replace // A.B with B. In this case the parent of A.B is A.B.C which is a // QualifiedNameSyntax var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right); return CanReplaceWithReducedName( qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken); } return false; } private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel) { if (!type.IsNullable()) { return false; } if (type.IsUnboundGenericType) { // Don't simplify unbound generic type "Nullable<>". return false; } if (InsideNameOfExpression(name, semanticModel)) { // Nullable<T> can't be simplified to T? in nameof expressions. return false; } if (!name.InsideCrefReference()) { // Nullable<T> can always be simplified to T? outside crefs. return true; } if (name.Parent is NameMemberCrefSyntax) return false; // Inside crefs, if the T in this Nullable{T} is being declared right here // then this Nullable{T} is not a constructed generic type and we should // not offer to simplify this to T?. // // For example, we should not offer the simplification in the following cases where // T does not bind to an existing type / type parameter in the user's code. // - <see cref="Nullable{T}"/> // - <see cref="System.Nullable{T}.Value"/> // // And we should offer the simplification in the following cases where SomeType and // SomeMethod bind to a type and method declared elsewhere in the users code. // - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/> var argument = type.TypeArguments.SingleOrDefault(); if (argument == null || argument.IsErrorType()) { return false; } var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault(); if (argumentDecl == null) { // The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)). return true; } return !name.Span.Contains(argumentDecl.Span); } private static bool CanReplaceWithPredefinedTypeKeywordInContext( NameSyntax name, SemanticModel semanticModel, out TypeSyntax replacementNode, ref TextSpan issueSpan, SyntaxKind keywordKind, string codeStyleOptionName) { replacementNode = CreatePredefinedTypeSyntax(name, keywordKind); issueSpan = name.Span; // we want to show the whole name expression as unnecessary var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel); if (canReduce) { replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName)); } return canReduce; } private static bool TryReduceAttributeSuffix( NameSyntax name, SyntaxToken identifierToken, out TypeSyntax replacementNode, out TextSpan issueSpan) { issueSpan = default; replacementNode = null; // we can try to remove the Attribute suffix if this is the attribute name if (SyntaxFacts.IsAttributeName(name)) { if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon()) { const string AttributeName = "Attribute"; // an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation)) { // weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code. // so we need another check for keywords manually. var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9); if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None) { return false; } // if this attribute name in source contained Unicode escaping, we will loose it now // because there is no easy way to determine the substring from identifier->ToString() // which would be needed to pass to SyntaxFactory.Identifier // The result is an unescaped Unicode character in source. // once we remove the Attribute suffix, we can't use an escaped identifier var newIdentifierToken = identifierToken.CopyAnnotationsTo( SyntaxFactory.Identifier( identifierToken.LeadingTrivia, newAttributeName, identifierToken.TrailingTrivia)); replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken) .WithLeadingTrivia(name.GetLeadingTrivia()); issueSpan = new TextSpan(identifierToken.Span.End - 9, 9); return true; } } } return false; } /// <summary> /// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax /// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name /// property. /// </summary> /// <param name="node"></param> /// <returns></returns> private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node) { var parent = node; while (parent != null) { switch (parent.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: node = parent; parent = parent.Parent; break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent; return object.Equals(namespaceDeclaration.Name, node); default: return false; } } return false; } public static bool CanReplaceWithReducedNameInContext( NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel) { // Check for certain things that would prevent us from reducing this name in this context. // For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply // not allowed in the C# grammar. if (IsNonNameSyntaxInUsingDirective(name, reducedName) || WillConflictWithExistingLocal(name, reducedName, semanticModel) || IsAmbiguousCast(name, reducedName) || IsNullableTypeInPointerExpression(reducedName) || IsNotNullableReplaceable(name, reducedName) || IsNonReducableQualifiedNameInUsingDirective(semanticModel, name)) { return false; } return true; } private static bool ContainsOpenName(NameSyntax name) { if (name is QualifiedNameSyntax qualifiedName) { return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right); } else if (name is GenericNameSyntax genericName) { return genericName.IsUnboundGenericName; } else { return false; } } private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken) { var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken); if (speculationAnalyzer.ReplacementChangesSemantics()) { return false; } return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel); } private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName) { if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType)) { if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument) return true; return name.IsLeftSideOfDot() || name.IsRightSideOfDot(); } return false; } private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode) { // Note: nullable type syntax is not allowed in pointer type syntax if (simplifiedNode.Kind() == SyntaxKind.NullableType && simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax)) { return true; } return false; } private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { return expression.IsParentKind(SyntaxKind.UsingDirective) && !(simplifiedNode is NameSyntax); } private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode) { // Can't simplify a type name in a cast expression if it would then cause the cast to be // parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to // (Bar)+1 then that's an arithmetic expression. if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) && castExpression.Type == expression) { var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode); var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString()); if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression)) { return true; } } return false; } private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name) { // Whereas most of the time we do not want to reduce namespace names, We will // make an exception for namespaces with the global:: alias. return IsQualifiedNameInUsingDirective(model, name) && !IsGlobalAliasQualifiedName(name); } private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name) { while (name.IsLeftSideOfQualifiedName()) { name = (NameSyntax)name.Parent; } if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) && usingDirective.Alias == null) { // We're a qualified name in a using. We don't want to reduce this name as people like // fully qualified names in usings so they can properly tell what the name is resolving // to. // However, if this name is actually referencing the special Script class, then we do // want to allow that to be reduced. return !IsInScriptClass(model, name); } return false; } private static bool IsGlobalAliasQualifiedName(NameSyntax name) { // Checks whether the `global::` alias is applied to the name return name is AliasQualifiedNameSyntax aliasName && aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword); } private static bool IsInScriptClass(SemanticModel model, NameSyntax name) { var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol; while (symbol != null) { if (symbol.IsScriptClass) { return true; } symbol = symbol.ContainingType; } return false; } private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel) { return !name.IsDirectChildOfMemberAccessExpression() && !name.InsideCrefReference() && !InsideNameOfExpression(name, semanticModel) && SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language); } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #pragma warning disable IDE0060 // Remove unused parameter - Majority of extension methods in this file have an unused 'SyntaxTree' this parameter for consistency with other Context related extension methods. namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal static partial class SyntaxTreeExtensions { public static bool IsAttributeNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); // cases: // [ | if (token.IsKind(SyntaxKind.OpenBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { return true; } // cases: // [Goo(1), | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { return true; } // cases: // [specifier: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.AttributeTargetSpecifier)) { return true; } // cases: // [Namespace.| if (token.Parent.IsKind(SyntaxKind.QualifiedName) && token.Parent.IsParentKind(SyntaxKind.Attribute)) { return true; } // cases: // [global::| if (token.Parent.IsKind(SyntaxKind.AliasQualifiedName) && token.Parent.IsParentKind(SyntaxKind.Attribute)) { return true; } return false; } public static bool IsGlobalMemberDeclarationContext( this SyntaxTree syntaxTree, int position, ISet<SyntaxKind> validModifiers, CancellationToken cancellationToken) { if (!syntaxTree.IsScript()) { return false; } var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); var parent = token.Parent; var modifierTokens = syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition); if (modifierTokens.IsEmpty()) { if (token.IsKind(SyntaxKind.CloseBracketToken) && parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && !IsGlobalAttributeList(attributeList)) { // Allow empty modifier tokens if we have an attribute list parent = attributeList.Parent; } else { return false; } } if (modifierTokens.IsSubsetOf(validModifiers)) { // the parent is the member // the grandparent is the container of the member // in interactive, it's possible that there might be an intervening "incomplete" member for partially // typed declarations that parse ambiguously. For example, "internal e". It's also possible for a // complete member to be parsed based on data after the caret, e.g. "unsafe $$ void L() { }". if (parent.IsKind(SyntaxKind.CompilationUnit) || (parent is MemberDeclarationSyntax && parent.IsParentKind(SyntaxKind.CompilationUnit))) { return true; } } return false; // Local functions static bool IsGlobalAttributeList(AttributeListSyntax attributeList) { if (attributeList.Target is { Identifier: { RawKind: var kind } }) { return kind == (int)SyntaxKind.AssemblyKeyword || kind == (int)SyntaxKind.ModuleKeyword; } return false; } } public static bool IsMemberDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // class C { // | // class C { // void Goo() { // } // | // class C { // int i; // | // class C { // [Goo] // | var originalToken = tokenOnLeftOfPosition; var token = originalToken; // If we're touching the right of an identifier, move back to // previous token. token = token.GetPreviousTokenIfTouchingWord(position); // class C { // | if (token.IsKind(SyntaxKind.OpenBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax) { return true; } } // class C { // int i; // | if (token.IsKind(SyntaxKind.SemicolonToken)) { if (token.Parent is MemberDeclarationSyntax && token.Parent.Parent is BaseTypeDeclarationSyntax) { return true; } } // class A { // class C {} // | // class C { // void Goo() { // } // | if (token.IsKind(SyntaxKind.CloseBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax && token.Parent.Parent is BaseTypeDeclarationSyntax) { // after a nested type return true; } else if (token.Parent is AccessorListSyntax) { // after a property return true; } else if ( token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { // after a method/operator/etc. return true; } } // namespace Goo { // [Bar] // | if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { // attributes belong to a member which itself is in a // container. // the parent is the attribute // the grandparent is the owner of the attribute // the great-grandparent is the container that the owner is in var container = token.Parent.Parent?.Parent; if (container is BaseTypeDeclarationSyntax) { return true; } } return false; } public static bool IsMemberDeclarationContext( this SyntaxTree syntaxTree, int position, CSharpSyntaxContext? contextOpt, ISet<SyntaxKind>? validModifiers, ISet<SyntaxKind>? validTypeDeclarations, bool canBePartial, CancellationToken cancellationToken) { var typeDecl = contextOpt != null ? contextOpt.ContainingTypeOrEnumDeclaration : syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken); if (typeDecl == null) { return false; } validTypeDeclarations ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (!validTypeDeclarations.Contains(typeDecl.Kind())) { return false; } // Check many of the simple cases first. var leftToken = contextOpt != null ? contextOpt.LeftToken : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = contextOpt != null ? contextOpt.TargetToken : leftToken.GetPreviousTokenIfTouchingWord(position); if (token.IsAnyAccessorDeclarationContext(position)) { return false; } if (syntaxTree.IsMemberDeclarationContext(position, leftToken)) { return true; } // A member can also show up after certain types of modifiers if (canBePartial && token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return true; } var modifierTokens = contextOpt != null ? contextOpt.PrecedingModifiers : syntaxTree.GetPrecedingModifiers(position, leftToken); if (modifierTokens.IsEmpty()) { return false; } validModifiers ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (modifierTokens.IsSubsetOf(validModifiers)) { var member = token.Parent; if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async", not followed by modifier: treat it as type if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token).Any(x => x == SyntaxKind.AsyncKeyword)) { return false; } // rule out async lambdas inside a method if (token.GetAncestor<StatementSyntax>() == null) { member = token.GetAncestor<MemberDeclarationSyntax>(); } } // cases: // public | // async | // public async | return member != null && member.Parent is BaseTypeDeclarationSyntax; } return false; } public static bool IsLambdaDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxKind otherModifier, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = leftToken.GetPreviousTokenIfTouchingWord(position); if (syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken)) { return true; } var modifierTokens = syntaxTree.GetPrecedingModifiers(position, token, out var beforeModifiersPosition); if (modifierTokens.Count == 1 && modifierTokens.Contains(otherModifier)) { if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async" not followed by modifier: treat as parameter name if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token).Contains(SyntaxKind.AsyncKeyword)) { return false; } } leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); return syntaxTree.IsExpressionContext(beforeModifiersPosition, token, attributes: false, cancellationToken); } return false; } public static bool IsLocalFunctionDeclarationContext( this SyntaxTree syntaxTree, int position, ISet<SyntaxKind> validModifiers, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = leftToken.GetPreviousTokenIfTouchingWord(position); // Local functions are always valid in a statement context. They are also valid for top-level statements (as // opposed to global functions which are defined in the global statement context of scripts). if (syntaxTree.IsStatementContext(position, leftToken, cancellationToken) || (!syntaxTree.IsScript() && syntaxTree.IsGlobalStatementContext(position, cancellationToken))) { return true; } // Also valid after certain modifiers var modifierTokens = syntaxTree.GetPrecedingModifiers( position, token, out var beforeModifiersPosition); if (modifierTokens.IsSubsetOf(validModifiers)) { if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async" not followed by modifier: treat as type if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token) .Contains(SyntaxKind.AsyncKeyword)) { return false; } } leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); // If one or more attribute lists are present before the caret, check to see if those attribute lists // were written in a local function declaration context. while (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList)) { beforeModifiersPosition = attributeList.OpenBracketToken.SpanStart; leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); } return syntaxTree.IsStatementContext(beforeModifiersPosition, token, cancellationToken) || (!syntaxTree.IsScript() && syntaxTree.IsGlobalStatementContext(beforeModifiersPosition, cancellationToken)); } return false; } public static bool IsTypeDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // root: | // extern alias a; // | // using Goo; // | // using Goo = Bar; // | // namespace N {} // | // namespace N { // | // class C {} // | // class C { // | // class C { // void Goo() { // } // | // class C { // int i; // | // class C { // [Goo] // | // (all the class cases apply to structs, interfaces and records). var originalToken = tokenOnLeftOfPosition; var token = originalToken; // If we're touching the right of an identifier, move back to // previous token. token = token.GetPreviousTokenIfTouchingWord(position); // a type decl can't come before usings/externs var nextToken = originalToken.GetNextToken(includeSkipped: true); if (nextToken.IsUsingOrExternKeyword() || (nextToken.Kind() == SyntaxKind.GlobalKeyword && nextToken.GetAncestor<UsingDirectiveSyntax>()?.GlobalKeyword == nextToken)) { return false; } // root: | if (token.IsKind(SyntaxKind.None)) { // root namespace // a type decl can't come before usings/externs if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit && (compilationUnit.Externs.Count > 0 || compilationUnit.Usings.Count > 0)) { return false; } return true; } if (token.IsKind(SyntaxKind.OpenBraceToken) && token.Parent is NamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; // extern alias a; // | // using Goo; // | // class C { // int i; // | // namespace NS; // | if (token.IsKind(SyntaxKind.SemicolonToken)) { if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective)) { return true; } else if (token.Parent is MemberDeclarationSyntax) { return true; } } // class C {} // | // namespace N {} // | // class C { // void Goo() { // } // | if (token.IsKind(SyntaxKind.CloseBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax) { return true; } else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } else if (token.Parent is AccessorListSyntax) { return true; } else if ( token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { return true; } } // namespace Goo { // [Bar] // | // namespace NS; // [Attr] // | if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { // assembly attributes belong to the containing compilation unit if (token.Parent.IsParentKind(SyntaxKind.CompilationUnit)) return true; // other attributes belong to a member which itself is in a // container. // the parent is the attribute // the grandparent is the owner of the attribute // the great-grandparent is the container that the owner is in var container = token.Parent?.Parent?.Parent; if (container is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; } return false; } public static bool IsTypeDeclarationContext( this SyntaxTree syntaxTree, int position, CSharpSyntaxContext? contextOpt, ISet<SyntaxKind>? validModifiers, ISet<SyntaxKind>? validTypeDeclarations, bool canBePartial, CancellationToken cancellationToken) { // We only allow nested types inside a class, struct, or interface, not inside a // an enum. var typeDecl = contextOpt != null ? contextOpt.ContainingTypeDeclaration : syntaxTree.GetContainingTypeDeclaration(position, cancellationToken); validTypeDeclarations ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (typeDecl != null) { if (!validTypeDeclarations.Contains(typeDecl.Kind())) { return false; } } // Check many of the simple cases first. var leftToken = contextOpt != null ? contextOpt.LeftToken : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); // If we're touching the right of an identifier, move back to // previous token. var token = contextOpt != null ? contextOpt.TargetToken : leftToken.GetPreviousTokenIfTouchingWord(position); if (token.IsAnyAccessorDeclarationContext(position)) { return false; } if (syntaxTree.IsTypeDeclarationContext(position, leftToken, cancellationToken)) { return true; } // A type can also show up after certain types of modifiers if (canBePartial && token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return true; } // using static | is never a type declaration context if (token.IsStaticKeywordInUsingDirective()) { return false; } var modifierTokens = contextOpt != null ? contextOpt.PrecedingModifiers : syntaxTree.GetPrecedingModifiers(position, leftToken); if (modifierTokens.IsEmpty()) { return false; } validModifiers ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (modifierTokens.IsProperSubsetOf(validModifiers)) { // the parent is the member // the grandparent is the container of the member var container = token.Parent?.Parent; // ref $$ // readonly ref $$ if (container.IsKind(SyntaxKind.IncompleteMember, out IncompleteMemberSyntax? incompleteMember)) return incompleteMember.Type.IsKind(SyntaxKind.RefType); if (container is CompilationUnitSyntax or NamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; } return false; } public static bool IsNamespaceContext( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // first do quick exit check if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsRightOfDotOrArrow(position, cancellationToken)) { return false; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); // global:: if (token.IsKind(SyntaxKind.ColonColonToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.GlobalKeyword)) { return true; } // using | // but not: // using | = Bar // Note: we take care of the using alias case in the IsTypeContext // call below. if (token.IsKind(SyntaxKind.UsingKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null) { if (token.GetNextToken(includeSkipped: true).Kind() != SyntaxKind.EqualsToken && usingDirective.Alias == null) { return true; } } } // using static | if (token.IsStaticKeywordInUsingDirective()) { return true; } // if it is not using directive location, most of places where // type can appear, namespace can appear as well return syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt); } public static bool IsNamespaceDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree.IsScript() || syntaxTree.IsInNonUserCode(position, cancellationToken)) return false; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token == default) return false; var declaration = token.GetAncestor<BaseNamespaceDeclarationSyntax>(); if (declaration?.NamespaceKeyword == token) return true; return declaration?.Name.Span.IntersectsWith(position) == true; } public static bool IsPartialTypeDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, [NotNullWhen(true)] out TypeDeclarationSyntax? declarationSyntax) { if (!syntaxTree.IsInNonUserCode(position, cancellationToken)) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if ((token.IsKind(SyntaxKind.ClassKeyword) || token.IsKind(SyntaxKind.StructKeyword) || token.IsKind(SyntaxKind.InterfaceKeyword)) && token.GetPreviousToken().IsKind(SyntaxKind.PartialKeyword)) { declarationSyntax = token.GetAncestor<TypeDeclarationSyntax>(); return declarationSyntax != null && declarationSyntax.Keyword == token; } } declarationSyntax = null; return false; } public static bool IsDefinitelyNotTypeContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsRightOfDotOrArrow(position, cancellationToken); } public static bool IsTypeContext( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // first do quick exit check if (syntaxTree.IsDefinitelyNotTypeContext(position, cancellationToken)) { return false; } // okay, now it is a case where we can't use parse tree (valid or error recovery) to // determine whether it is a right place to put type. use lex based one Cyrus created. var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.CaseKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.EventKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || syntaxTree.IsAttributeNameContext(position, cancellationToken) || syntaxTree.IsBaseClassOrInterfaceContext(position, cancellationToken) || syntaxTree.IsCatchVariableDeclarationContext(position, cancellationToken) || syntaxTree.IsDefiniteCastTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDelegateReturnTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) || syntaxTree.IsPrimaryFunctionExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt) || syntaxTree.IsFunctionPointerTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsFixedVariableDeclarationContext(position, tokenOnLeftOfPosition) || syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsIsOrAsTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsLocalVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsObjectCreationTypeContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsParameterTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsStatementContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsGlobalStatementContext(position, cancellationToken) || syntaxTree.IsTypeParameterConstraintContext(position, tokenOnLeftOfPosition) || syntaxTree.IsUsingAliasContext(position, cancellationToken) || syntaxTree.IsUsingStaticContext(position, cancellationToken) || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || syntaxTree.IsPossibleTupleContext(tokenOnLeftOfPosition, position) || syntaxTree.IsMemberDeclarationContext( position, contextOpt: null, validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } public static bool IsBaseClassOrInterfaceContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // class C : | // class C : Bar, | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.ColonToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.BaseList)) { return true; } } return false; } public static bool IsUsingAliasContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // using Goo = | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.EqualsToken) && token.GetAncestor<UsingDirectiveSyntax>() != null) { return true; } return false; } public static bool IsUsingStaticContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // using static | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); return token.IsStaticKeywordInUsingDirective(); } public static bool IsTypeArgumentOfConstraintClause( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // cases: // where | // class Goo<T> : Object where | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return true; } if (token.IsKind(SyntaxKind.IdentifierToken) && token.HasMatchingText(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.SimpleBaseType) && token.Parent.Parent.IsParentKind(SyntaxKind.BaseList)) { return true; } return false; } public static bool IsTypeParameterConstraintStartContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // where T : | var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.ColonToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IdentifierToken) && token.GetPreviousToken(includeSkipped: true).GetPreviousToken().IsKind(SyntaxKind.WhereKeyword)) { return true; } return false; } public static bool IsTypeParameterConstraintContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (syntaxTree.IsTypeParameterConstraintStartContext(position, tokenOnLeftOfPosition)) { return true; } var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Can't come after new() // // where T : | // where T : class, | // where T : struct, | // where T : Goo, | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax? constraintClause)) { // Check if there's a 'new()' constraint. If there isn't, or we're before it, then // this is a type parameter constraint context. var firstConstructorConstraint = constraintClause.Constraints.FirstOrDefault(t => t is ConstructorConstraintSyntax); if (firstConstructorConstraint == null || firstConstructorConstraint.SpanStart > token.Span.End) { return true; } } return false; } public static bool IsTypeOfExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.TypeOfExpression)) { return true; } return false; } public static bool IsDefaultExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.DefaultExpression)) { return true; } return false; } public static bool IsSizeOfExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.SizeOfExpression)) { return true; } return false; } public static bool IsFunctionPointerTypeArgumentContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.CommaToken: return token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList); } return token switch { // ref modifiers { Parent: { RawKind: (int)SyntaxKind.FunctionPointerParameter } } => true, // Regular type specifiers { Parent: TypeSyntax { Parent: { RawKind: (int)SyntaxKind.FunctionPointerParameter } } } => true, _ => false }; } public static bool IsGenericTypeArgumentContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // cases: // Goo<| // Goo<Bar,| // Goo<Bar<Baz<int[],| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.LessThanToken && token.Kind() != SyntaxKind.CommaToken) { return false; } if (token.Parent is TypeArgumentListSyntax) { // Easy case, it was known to be a generic name, so this is a type argument context. return true; } if (!syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var nameToken)) { return false; } if (!(nameToken.Parent is NameSyntax name)) { return false; } // Looks viable! If they provided a binding, then check if it binds properly to // an actual generic entity. if (semanticModelOpt == null) { // No binding. Just make the decision based on the syntax tree. return true; } // '?' is syntactically ambiguous in incomplete top-level statements: // // T ? goo<| // // Might be an incomplete conditional expression or an incomplete declaration of a method returning a nullable type. // Bind T to see if it is a type. If it is we don't show signature help. if (name.IsParentKind(SyntaxKind.LessThanExpression) && name.Parent.IsParentKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax? conditional) && conditional.IsParentKind(SyntaxKind.ExpressionStatement) && conditional.Parent.IsParentKind(SyntaxKind.GlobalStatement)) { var conditionOrType = semanticModelOpt.GetSymbolInfo(conditional.Condition, cancellationToken); if (conditionOrType.GetBestOrAllSymbols().FirstOrDefault() is { Kind: SymbolKind.NamedType }) { return false; } } var symbols = semanticModelOpt.LookupName(nameToken, cancellationToken); return symbols.Any(s => { switch (s) { case INamedTypeSymbol nt: return nt.Arity > 0; case IMethodSymbol m: return m.Arity > 0; default: return false; } }); } public static bool IsParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, bool includeOperators, out int parameterIndex, out SyntaxKind previousModifier) { // cases: // Goo(| // Goo(int i, | // Goo([Bar]| var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); parameterIndex = -1; previousModifier = SyntaxKind.None; if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = 0; return true; } if (token.IsKind(SyntaxKind.LessThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList)) { parameterIndex = 0; return true; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ParameterList, out ParameterListSyntax? parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { var commaIndex = parameterList.Parameters.GetWithSeparators().IndexOf(token); parameterIndex = commaIndex / 2 + 1; return true; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList, out FunctionPointerParameterListSyntax? funcPtrParamList)) { var commaIndex = funcPtrParamList.Parameters.GetWithSeparators().IndexOf(token); parameterIndex = commaIndex / 2 + 1; return true; } if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList) && token.Parent.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax? parameter) && parameter.IsParentKind(SyntaxKind.ParameterList, out parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = parameterList.Parameters.IndexOf(parameter); return true; } if (token.IsKind(SyntaxKind.RefKeyword, SyntaxKind.InKeyword, SyntaxKind.OutKeyword, SyntaxKind.ThisKeyword, SyntaxKind.ParamsKeyword) && token.Parent.IsKind(SyntaxKind.Parameter, out parameter) && parameter.IsParentKind(SyntaxKind.ParameterList, out parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = parameterList.Parameters.IndexOf(parameter); previousModifier = token.Kind(); return true; } return false; } public static bool IsParamsModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, includeOperators: false, out _, out var previousModifier) && previousModifier == SyntaxKind.None) { return true; } var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { return token.Parent.IsKind(SyntaxKind.BracketedParameterList); } return false; } public static bool IsDelegateReturnTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.DelegateKeyword) && token.Parent.IsKind(SyntaxKind.DelegateDeclaration)) { return true; } return false; } public static bool IsImplicitOrExplicitOperatorTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OperatorKeyword)) { if (token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ImplicitKeyword) || token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ExplicitKeyword)) { return true; } } return false; } public static bool IsParameterTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, includeOperators: true, out _, out _)) { return true; } // int this[ | // int this[int i, | if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList)) { return true; } } return false; } public static bool IsPossibleExtensionMethodContext(this SyntaxTree syntaxTree, SyntaxToken tokenOnLeftOfPosition) { var method = tokenOnLeftOfPosition.Parent.GetAncestorOrThis<MethodDeclarationSyntax>(); var typeDecl = method.GetAncestorOrThis<TypeDeclarationSyntax>(); return method != null && typeDecl != null && typeDecl.IsKind(SyntaxKind.ClassDeclaration) && method.Modifiers.Any(SyntaxKind.StaticKeyword) && typeDecl.Modifiers.Any(SyntaxKind.StaticKeyword); } public static bool IsPossibleLambdaParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList) && token.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression)) { return true; } // TODO(cyrusn): Tie into semantic analysis system to only // consider this a lambda if this is a location where the // lambda's type would be inferred because of a delegate // or Expression<T> type. if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression) || token.Parent.IsKind(SyntaxKind.TupleExpression)) { return true; } } return false; } public static bool IsAnonymousMethodParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList) && token.Parent.IsParentKind(SyntaxKind.AnonymousMethodExpression)) { return true; } } return false; } public static bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword) || token.IsKind(SyntaxKind.OutKeyword)) { position = token.SpanStart; tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); } if (IsAnonymousMethodParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition) || IsPossibleLambdaParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition)) { return true; } return false; } /// <summary> /// Are you possibly typing a tuple type or expression? /// This is used to suppress colon as a completion trigger (so that you can type element names). /// This is also used to recommend some keywords (like var). /// </summary> public static bool IsPossibleTupleContext(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // ($$ // (a, $$ if (IsPossibleTupleOpenParenOrComma(leftToken)) { return true; } // ((a, b) $$ // (..., (a, b) $$ if (leftToken.IsKind(SyntaxKind.CloseParenToken)) { if (leftToken.Parent.IsKind( SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.TupleType)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } } // (a $$ // (..., b $$ if (leftToken.IsKind(SyntaxKind.IdentifierToken)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent!); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } // (a.b $$ // (..., a.b $$ if (leftToken.IsKind(SyntaxKind.IdentifierToken) && leftToken.Parent.IsKind(SyntaxKind.IdentifierName) && leftToken.Parent.Parent.IsKind(SyntaxKind.QualifiedName, SyntaxKind.SimpleMemberAccessExpression)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent.Parent); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } return false; } public static bool IsAtStartOfPattern(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); if (leftToken.IsKind(SyntaxKind.OpenParenToken)) { if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenthesizedExpression)) { // If we're dealing with an expression surrounded by one or more sets of open parentheses, we need to // walk up the parens in order to see if we're actually at the start of a valid pattern or not. return IsAtStartOfPattern(syntaxTree, parenthesizedExpression.GetFirstToken().GetPreviousToken(), parenthesizedExpression.SpanStart); } // e is ((($$ 1 or 2))) if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedPattern)) { return true; } } // case $$ // is $$ if (leftToken.IsKind(SyntaxKind.CaseKeyword, SyntaxKind.IsKeyword)) { return true; } // e switch { $$ // e switch { ..., $$ if (leftToken.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.SwitchExpression)) { return true; } // e is ($$ // e is (..., $$ if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.PositionalPatternClause)) { return true; } // e is { P: $$ // e is { ..., P: $$ // e is { ..., P.P2: $$ if (leftToken.IsKind(SyntaxKind.ColonToken) && leftToken.Parent.IsKind(SyntaxKind.NameColon, SyntaxKind.ExpressionColon) && leftToken.Parent.IsParentKind(SyntaxKind.Subpattern)) { return true; } // e is 1 and $$ // e is 1 or $$ if (leftToken.IsKind(SyntaxKind.AndKeyword) || leftToken.IsKind(SyntaxKind.OrKeyword)) { return leftToken.Parent is BinaryPatternSyntax; } // e is not $$ if (leftToken.IsKind(SyntaxKind.NotKeyword) && leftToken.Parent.IsKind(SyntaxKind.NotPattern)) { return true; } return false; } public static bool IsAtEndOfPattern(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { var originalLeftToken = leftToken; leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // For instance: // e is { A.$$ } if (leftToken.IsKind(SyntaxKind.DotToken)) { return false; } var patternSyntax = leftToken.GetAncestor<PatternSyntax>(); if (patternSyntax != null) { var lastTokenInPattern = patternSyntax.GetLastToken(); // This check should cover the majority of cases, e.g.: // e is 1 $$ // e is >= 0 $$ // e is { P: (1 $$ // e is { P: (1) $$ if (leftToken == lastTokenInPattern) { // Patterns such as 'e is not $$', 'e is 1 or $$', 'e is ($$', and 'e is null or global::$$' should be invalid here // as they are incomplete patterns. return !(leftToken.IsKind(SyntaxKind.OrKeyword) || leftToken.IsKind(SyntaxKind.AndKeyword) || leftToken.IsKind(SyntaxKind.NotKeyword) || leftToken.IsKind(SyntaxKind.OpenParenToken) || leftToken.IsKind(SyntaxKind.ColonColonToken)); } // We want to make sure that IsAtEndOfPattern returns true even when the user is in the middle of typing a keyword // after a pattern. // For example, with the keyword 'and', we want to make sure that 'e is int an$$' is still recognized as valid. if (lastTokenInPattern.Parent is SingleVariableDesignationSyntax variableDesignationSyntax && originalLeftToken.Parent == variableDesignationSyntax) { return patternSyntax is DeclarationPatternSyntax || patternSyntax is RecursivePatternSyntax; } } // e is C.P $$ // e is int $$ if (leftToken.IsLastTokenOfNode<TypeSyntax>(out var typeSyntax)) { // If typeSyntax is part of a qualified name, we want to get the fully-qualified name so that we can // later accurately perform the check comparing the right side of the BinaryExpressionSyntax to // the typeSyntax. while (typeSyntax.Parent is TypeSyntax parentTypeSyntax) { typeSyntax = parentTypeSyntax; } if (typeSyntax.Parent is BinaryExpressionSyntax binaryExpressionSyntax && binaryExpressionSyntax.OperatorToken.IsKind(SyntaxKind.IsKeyword) && binaryExpressionSyntax.Right == typeSyntax && !typeSyntax.IsVar) { return true; } } // We need to include a special case for switch statement cases, as some are not currently parsed as patterns, e.g. case (1 $$ if (IsAtEndOfSwitchStatementPattern(leftToken)) { return true; } return false; static bool IsAtEndOfSwitchStatementPattern(SyntaxToken leftToken) { SyntaxNode? node = leftToken.Parent as ExpressionSyntax; if (node == null) return false; // Walk up the right edge of all complete expressions. while (node is ExpressionSyntax && node.GetLastToken(includeZeroWidth: true) == leftToken) node = node.GetRequiredParent(); // Getting rid of the extra parentheses to deal with cases such as 'case (((1 $$' while (node is ParenthesizedExpressionSyntax) node = node.GetRequiredParent(); // case (1 $$ if (node is CaseSwitchLabelSyntax { Parent: SwitchSectionSyntax }) return true; return false; } } private static SyntaxToken FindTokenOnLeftOfNode(SyntaxNode node) => node.FindTokenOnLeftOfPosition(node.SpanStart); public static bool IsPossibleTupleOpenParenOrComma(this SyntaxToken possibleCommaOrParen) { if (!possibleCommaOrParen.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return false; } if (possibleCommaOrParen.Parent.IsKind( SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.TupleType, SyntaxKind.CastExpression)) { return true; } // in script if (possibleCommaOrParen.Parent.IsKind(SyntaxKind.ParameterList) && possibleCommaOrParen.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression, out ParenthesizedLambdaExpressionSyntax? parenthesizedLambda)) { if (parenthesizedLambda.ArrowToken.IsMissing) { return true; } } return false; } /// <summary> /// Are you possibly in the designation part of a deconstruction? /// This is used to enter suggestion mode (suggestions become soft-selected). /// </summary> public static bool IsPossibleDeconstructionDesignation(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // The well-formed cases: // var ($$, y) = e; // (var $$, var y) = e; if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation) || leftToken.Parent.IsParentKind(SyntaxKind.ParenthesizedVariableDesignation)) { return true; } // (var $$, var y) // (var x, var y) if (syntaxTree.IsPossibleTupleContext(leftToken, position) && !IsPossibleTupleOpenParenOrComma(leftToken)) { return true; } // var ($$) // var (x, $$) if (IsPossibleVarDeconstructionOpenParenOrComma(leftToken)) { return true; } // var (($$), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken) && leftToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent))) { return true; } } // var ((x, $$), y) // var (($$, x), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.TupleExpression)) { if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent))) { return true; } } // foreach (var ($$ // foreach (var ((x, $$), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { var outer = UnwrapPossibleTuple(leftToken.Parent!); if (outer.Parent.IsKind(SyntaxKind.ForEachStatement, out ForEachStatementSyntax? @foreach)) { if (@foreach.Expression == outer && @foreach.Type.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName) && identifierName.Identifier.ValueText == "var") { return true; } } } return false; } /// <summary> /// If inside a parenthesized or tuple expression, unwrap the nestings and return the container. /// </summary> private static SyntaxNode UnwrapPossibleTuple(SyntaxNode node) { while (true) { if (node.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { node = node.Parent; continue; } if (node.Parent.IsKind(SyntaxKind.Argument) && node.Parent.Parent.IsKind(SyntaxKind.TupleExpression)) { node = node.Parent.Parent; continue; } return node; } } private static bool IsPossibleVarDeconstructionOpenParenOrComma(SyntaxToken leftToken) { if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.ArgumentList) && leftToken.Parent.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation)) { if (invocation.Expression.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName) && identifierName.Identifier.ValueText == "var") { return true; } } return false; } public static bool HasNames(this TupleExpressionSyntax tuple) => tuple.Arguments.Any(a => a.NameColon != null); public static bool IsValidContextForFromClause( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { if (syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) && !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition)) { return true; } // cases: // var q = | // var q = f| // // var q = from x in y // | // // var q = from x in y // f| // // this list is *not* exhaustive. // the first two are handled by 'IsExpressionContext' var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } public static bool IsValidContextForJoinClause( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } public static bool IsDeclarationExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // M(out var // var x = var var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OutKeyword) && token.Parent.IsKind(SyntaxKind.Argument)) { return true; } if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.EqualsValueClause) && token.Parent.IsParentKind(SyntaxKind.VariableDeclarator)) { return true; } return false; } public static bool IsLocalVariableDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // const var // out var // for (var // foreach (var // await foreach (var // using (var // await using (var // from var // join var var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); // const | if (token.IsKind(SyntaxKind.ConstKeyword) && token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement)) { return true; } // ref | // ref readonly | // for ( ref | // foreach ( ref | x if (token.IsKind(SyntaxKind.RefKeyword, SyntaxKind.ReadOnlyKeyword)) { var parent = token.Parent; if (parent.IsKind(SyntaxKind.RefType, SyntaxKind.RefExpression, SyntaxKind.LocalDeclarationStatement)) { if (parent.IsParentKind(SyntaxKind.VariableDeclaration) && parent.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.ForEachVariableStatement)) { return true; } if (parent.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement)) { return true; } } } // out | if (token.IsKind(SyntaxKind.OutKeyword) && token.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.RefKindKeyword == token) { return true; } if (token.IsKind(SyntaxKind.OpenParenToken)) { // for ( | // foreach ( | // await foreach ( | // using ( | // await using ( | var previous = token.GetPreviousToken(includeSkipped: true); if (previous.IsKind(SyntaxKind.ForKeyword) || previous.IsKind(SyntaxKind.ForEachKeyword) || previous.IsKind(SyntaxKind.UsingKeyword)) { return true; } } // from | var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken); if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) && syntaxTree.IsValidContextForFromClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken)) { return true; } // join | if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.JoinKeyword) && syntaxTree.IsValidContextForJoinClause(token.SpanStart, tokenOnLeftOfStart)) { return true; } return false; } public static bool IsFixedVariableDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // fixed (var var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.FixedKeyword)) { return true; } return false; } public static bool IsCatchVariableDeclarationContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // cases: // catch (var var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CatchKeyword)) { return true; } return false; } public static bool IsIsOrAsTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.IsKeyword) || token.IsKind(SyntaxKind.AsKeyword)) { return true; } return false; } public static bool IsObjectCreationTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.NewKeyword)) { // we can follow a 'new' if it's the 'new' for an expression. var start = token.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); return IsNonConstantExpressionContext(syntaxTree, token.SpanStart, tokenOnLeftOfStart, cancellationToken) || syntaxTree.IsStatementContext(token.SpanStart, tokenOnLeftOfStart, cancellationToken) || syntaxTree.IsGlobalStatementContext(token.SpanStart, cancellationToken); } return false; } private static bool IsNonConstantExpressionContext(SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { return syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken) && !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); return syntaxTree.IsPreProcessorDirectiveContext(position, leftToken, cancellationToken); } public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return IsPreProcessorKeywordContext( syntaxTree, position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true)); } public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition) { // cases: // #| // #d| // # | // # d| // note: comments are not allowed between the # and item. var token = preProcessorTokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.HashToken)) { return true; } return false; } public static bool IsStatementContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { #if false // we're in a statement if the thing that comes before allows for // statements to follow. Or if we're on a just started identifier // in the first position where a statement can go. if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); return token.IsBeginningOfStatementContext(); } public static bool IsGlobalStatementContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { #if false if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.None)) { // global statements can't come before usings/externs if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit && (compilationUnit.Externs.Count > 0 || compilationUnit.Usings.Count > 0)) { return false; } return true; } return token.IsBeginningOfGlobalStatementContext(); } public static bool IsInstanceContext(this SyntaxTree syntaxTree, SyntaxToken targetToken, SemanticModel semanticModel, CancellationToken cancellationToken) { #if false if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var enclosingSymbol = semanticModel.GetEnclosingSymbol(targetToken.SpanStart, cancellationToken); while (enclosingSymbol is IMethodSymbol method && (method.MethodKind == MethodKind.LocalFunction || method.MethodKind == MethodKind.AnonymousFunction)) { if (method.IsStatic) { return false; } // It is allowed to reference the instance (`this`) within a local function or anonymous function, as long as the containing method allows it enclosingSymbol = enclosingSymbol.ContainingSymbol; } return enclosingSymbol is { IsStatic: false }; } public static bool IsPossibleCastTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OpenParenToken) && syntaxTree.IsExpressionContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), false, cancellationToken)) { return true; } return false; } public static bool IsDefiniteCastTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.CastExpression)) { return true; } return false; } public static bool IsConstantExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (IsAtStartOfPattern(syntaxTree, tokenOnLeftOfPosition, position)) { return true; } var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); // goto case | if (token.IsKind(SyntaxKind.CaseKeyword) && token.Parent.IsKind(SyntaxKind.GotoCaseStatement)) { return true; } if (token.IsKind(SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue)) { if (equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) && equalsValue.Parent.IsParentKind(SyntaxKind.VariableDeclaration)) { // class C { const int i = | var fieldDeclaration = equalsValue.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null) { return fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword); } // void M() { const int i = | var localDeclaration = equalsValue.GetAncestor<LocalDeclarationStatementSyntax>(); if (localDeclaration != null) { return localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword); } } // enum E { A = | if (equalsValue.IsParentKind(SyntaxKind.EnumMemberDeclaration)) { return true; } // void M(int i = | if (equalsValue.IsParentKind(SyntaxKind.Parameter)) { return true; } } // [Goo( | // [Goo(x, | if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) && (token.IsKind(SyntaxKind.CommaToken) || token.IsKind(SyntaxKind.OpenParenToken))) { return true; } // [Goo(x: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.NameColon) && token.Parent.IsParentKind(SyntaxKind.AttributeArgument)) { return true; } // [Goo(X = | if (token.IsKind(SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.NameEquals) && token.Parent.IsParentKind(SyntaxKind.AttributeArgument)) { return true; } // TODO: Fixed-size buffer declarations return false; } public static bool IsLabelContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var gotoStatement = token.GetAncestor<GotoStatementSyntax>(); if (gotoStatement != null) { if (gotoStatement.GotoKeyword == token) { return true; } if (gotoStatement.Expression != null && !gotoStatement.Expression.IsMissing && gotoStatement.Expression is IdentifierNameSyntax && ((IdentifierNameSyntax)gotoStatement.Expression).Identifier == token && token.IntersectsWith(position)) { return true; } } return false; } public static bool IsExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, bool attributes, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // cases: // var q = | // var q = a| // this list is *not* exhaustive. var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.GetAncestor<ConditionalDirectiveTriviaSyntax>() != null) { return false; } if (!attributes) { if (token.GetAncestor<AttributeListSyntax>() != null) { return false; } } if (syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition)) { return true; } // no expressions after . :: -> if (token.IsKind(SyntaxKind.DotToken) || token.IsKind(SyntaxKind.ColonColonToken) || token.IsKind(SyntaxKind.MinusGreaterThanToken)) { return false; } // Normally you can have any sort of expression after an equals. However, this does not // apply to a "using Goo = ..." situation. if (token.IsKind(SyntaxKind.EqualsToken)) { if (token.Parent.IsKind(SyntaxKind.NameEquals) && token.Parent.IsParentKind(SyntaxKind.UsingDirective)) { return false; } } // q = | // q -= | // q *= | // q += | // q /= | // q ^= | // q %= | // q &= | // q |= | // q <<= | // q >>= | // q ??= | if (token.IsKind(SyntaxKind.EqualsToken) || token.IsKind(SyntaxKind.MinusEqualsToken) || token.IsKind(SyntaxKind.AsteriskEqualsToken) || token.IsKind(SyntaxKind.PlusEqualsToken) || token.IsKind(SyntaxKind.SlashEqualsToken) || token.IsKind(SyntaxKind.ExclamationEqualsToken) || token.IsKind(SyntaxKind.CaretEqualsToken) || token.IsKind(SyntaxKind.AmpersandEqualsToken) || token.IsKind(SyntaxKind.BarEqualsToken) || token.IsKind(SyntaxKind.PercentEqualsToken) || token.IsKind(SyntaxKind.LessThanLessThanEqualsToken) || token.IsKind(SyntaxKind.GreaterThanGreaterThanEqualsToken) || token.IsKind(SyntaxKind.QuestionQuestionEqualsToken)) { return true; } // ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } // - | // + | // ~ | // ! | if (token.Parent is PrefixUnaryExpressionSyntax prefix) { return prefix.OperatorToken == token; } // not sure about these: // ++ | // -- | #if false token.Kind == SyntaxKind.PlusPlusToken || token.Kind == SyntaxKind.DashDashToken) #endif // await | if (token.Parent is AwaitExpressionSyntax awaitExpression) { return awaitExpression.AwaitKeyword == token; } // Check for binary operators. // Note: // - We handle < specially as it can be ambiguous with generics. // - We handle * specially because it can be ambiguous with pointer types. // a * // a / // a % // a + // a - // a << // a >> // a < // a > // a && // a || // a & // a | // a ^ if (token.Parent is BinaryExpressionSyntax binary) { // If the client provided a binding, then check if this is actually generic. If so, // then this is not an expression context. i.e. if we have "Goo < |" then it could // be an expression context, or it could be a type context if Goo binds to a type or // method. if (semanticModelOpt != null && syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt)) { return false; } if (binary.OperatorToken == token) { // If this is a multiplication expression and a semantic model was passed in, // check to see if the expression to the left is a type name. If it is, treat // this as a pointer type. if (token.IsKind(SyntaxKind.AsteriskToken) && semanticModelOpt != null) { if (binary.Left is TypeSyntax type && type.IsPotentialTypeName(semanticModelOpt, cancellationToken)) { return false; } } return true; } } // Special case: // Goo * bar // Goo ? bar // This parses as a local decl called bar of type Goo* or Goo? if (tokenOnLeftOfPosition.IntersectsWith(position) && tokenOnLeftOfPosition.IsKind(SyntaxKind.IdentifierToken)) { var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true); if (previousToken.IsKind(SyntaxKind.AsteriskToken) || previousToken.IsKind(SyntaxKind.QuestionToken)) { if (previousToken.Parent.IsKind(SyntaxKind.PointerType) || previousToken.Parent.IsKind(SyntaxKind.NullableType)) { var type = previousToken.Parent as TypeSyntax; if (type.IsParentKind(SyntaxKind.VariableDeclaration) && type.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? declStatement)) { // note, this doesn't apply for cases where we know it // absolutely is not multiplication or a conditional expression. var underlyingType = type is PointerTypeSyntax pointerType ? pointerType.ElementType : ((NullableTypeSyntax)type).ElementType; if (!underlyingType.IsPotentialTypeName(semanticModelOpt, cancellationToken)) { return true; } } } } } // new int[| // new int[expr, | if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier)) { return true; } } // goo ? | if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent.IsKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax? conditionalExpression)) { // If the condition is simply a TypeSyntax that binds to a type, treat this as a nullable type. return !(conditionalExpression.Condition is TypeSyntax type) || !type.IsPotentialTypeName(semanticModelOpt, cancellationToken); } // goo ? bar : | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.ConditionalExpression)) { return true; } // typeof(| // default(| // sizeof(| if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression)) { return false; } } // var(| // var(id, | // Those are more likely to be deconstruction-declarations being typed than invocations a method "var" if (token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && token.IsInvocationOfVarExpression()) { return false; } // Goo(| // Goo(expr, | // this[| // var t = (1, | // var t = (| , 2) if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.TupleExpression)) { return true; } } // [Goo(| // [Goo(expr, | if (attributes) { if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList)) { return true; } } } // Goo(ref | // Goo(in | // Goo(out | // ref var x = ref | if (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword) || token.IsKind(SyntaxKind.OutKeyword)) { if (token.Parent.IsKind(SyntaxKind.Argument)) { return true; } else if (token.Parent.IsKind(SyntaxKind.RefExpression)) { // ( ref | // parenthesized expressions can't directly contain RefExpression, unless the user is typing an incomplete lambda expression. if (token.Parent.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return false; } return true; } } // Goo(bar: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.NameColon) && token.Parent.IsParentKind(SyntaxKind.Argument)) { return true; } // a => | if (token.IsKind(SyntaxKind.EqualsGreaterThanToken)) { return true; } // new List<int> { | // new List<int> { expr, | if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent is InitializerExpressionSyntax) { // The compiler treats the ambiguous case as an object initializer, so we'll say // expressions are legal here if (token.Parent.IsKind(SyntaxKind.ObjectInitializerExpression) && token.IsKind(SyntaxKind.OpenBraceToken)) { // In this position { a$$ =, the user is trying to type an object initializer. if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().IsKind(SyntaxKind.EqualsToken)) { return false; } return true; } // Perform a semantic check to determine whether or not the type being created // can support a collection initializer. If not, this must be an object initializer // and can't be an expression context. if (semanticModelOpt != null && token.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation)) { var containingSymbol = semanticModelOpt.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (semanticModelOpt.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol is ITypeSymbol type && !type.CanSupportCollectionInitializer(containingSymbol)) { return false; } } return true; } } // for (; | // for (; ; | if (token.IsKind(SyntaxKind.SemicolonToken) && token.Parent.IsKind(SyntaxKind.ForStatement, out ForStatementSyntax? forStatement)) { if (token == forStatement.FirstSemicolonToken || token == forStatement.SecondSemicolonToken) { return true; } } // for ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ForStatement, out forStatement) && token == forStatement.OpenParenToken) { return true; } // for (; ; Goo(), | // for ( Goo(), | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ForStatement)) { return true; } // foreach (var v in | // await foreach (var v in | // from a in | // join b in | if (token.IsKind(SyntaxKind.InKeyword)) { if (token.Parent.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement, SyntaxKind.FromClause, SyntaxKind.JoinClause)) { return true; } } // join x in y on | // join x in y on a equals | if (token.IsKind(SyntaxKind.OnKeyword) || token.IsKind(SyntaxKind.EqualsKeyword)) { if (token.Parent.IsKind(SyntaxKind.JoinClause)) { return true; } } // where | if (token.IsKind(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.WhereClause)) { return true; } // orderby | // orderby a, | if (token.IsKind(SyntaxKind.OrderByKeyword) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } } // select | if (token.IsKind(SyntaxKind.SelectKeyword) && token.Parent.IsKind(SyntaxKind.SelectClause)) { return true; } // group | // group expr by | if (token.IsKind(SyntaxKind.GroupKeyword) || token.IsKind(SyntaxKind.ByKeyword)) { if (token.Parent.IsKind(SyntaxKind.GroupClause)) { return true; } } // return | // yield return | // but not: [return | if (token.IsKind(SyntaxKind.ReturnKeyword)) { if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken) { return true; } } // throw | if (token.IsKind(SyntaxKind.ThrowKeyword)) { return true; } // while ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhileKeyword)) { return true; } // todo: handle 'for' cases. // using ( | // await using ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.UsingStatement)) { return true; } // lock ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.LockKeyword)) { return true; } // lock ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IfKeyword)) { return true; } // switch ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.SwitchKeyword)) { return true; } // checked ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CheckedKeyword)) { return true; } // unchecked ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UncheckedKeyword)) { return true; } // when ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhenKeyword)) { return true; } // case ... when | if (token.IsKind(SyntaxKind.WhenKeyword) && token.Parent.IsKind(SyntaxKind.WhenClause)) { return true; } // (SomeType) | if (token.IsAfterPossibleCast()) { return true; } // In anonymous type initializer. // // new { | We allow new inside of anonymous object member declarators, so that the user // can dot into a member afterward. For example: // // var a = new { new C().Goo }; if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) { return true; } } // $"{ | // $@"{ | // $"{x} { | // $@"{x} { | if (token.IsKind(SyntaxKind.OpenBraceToken)) { return token.Parent.IsKind(SyntaxKind.Interpolation, out InterpolationSyntax? interpolation) && interpolation.OpenBraceToken == token; } return false; } public static bool IsInvocationOfVarExpression(this SyntaxToken token) => token.Parent.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression.ToString() == "var"; public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel? semanticModelOpt = null, CancellationToken cancellationToken = default) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); // nameof(Goo.| // nameof(Goo.Bar.| // Locate the open paren. if (token.IsKind(SyntaxKind.DotToken)) { // Could have been parsed as member access if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var parentMemberAccess = token.Parent; while (parentMemberAccess.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { parentMemberAccess = parentMemberAccess.Parent; } if (parentMemberAccess.Parent.IsKind(SyntaxKind.Argument) && parentMemberAccess.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault())) { token = ((ArgumentListSyntax)parentMemberAccess.Parent.Parent!).OpenParenToken; } } // Could have been parsed as a qualified name. if (token.Parent.IsKind(SyntaxKind.QualifiedName)) { var parentQualifiedName = token.Parent; while (parentQualifiedName.Parent.IsKind(SyntaxKind.QualifiedName)) { parentQualifiedName = parentQualifiedName.Parent; } if (parentQualifiedName.Parent.IsKind(SyntaxKind.Argument) && parentQualifiedName.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault())) { token = ((ArgumentListSyntax)parentQualifiedName.Parent.Parent!).OpenParenToken; } } } ExpressionSyntax? parentExpression = null; // if the nameof expression has a missing close paren, it is parsed as an invocation expression. if (token.Parent.IsKind(SyntaxKind.ArgumentList) && token.Parent.Parent is InvocationExpressionSyntax invocationExpression && invocationExpression.IsNameOfInvocation()) { parentExpression = invocationExpression; } if (parentExpression != null) { if (semanticModelOpt == null) { return true; } return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null; } return false; } public static bool IsIsOrAsOrSwitchOrWithExpressionContext( this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // expr | var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Not if the position is a numeric literal if (token.IsKind(SyntaxKind.NumericLiteralToken)) { return false; } if (token.GetAncestor<BlockSyntax>() == null && token.GetAncestor<ArrowExpressionClauseSyntax>() == null) { return false; } // is/as/with are valid after expressions. if (token.IsLastTokenOfNode<ExpressionSyntax>(out var expression)) { // 'is/as/with' not allowed after a anonymous-method/lambda/method-group. if (expression.IsAnyLambdaOrAnonymousMethod()) return false; var symbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (symbol is IMethodSymbol) return false; // However, many names look like expressions. For example: // foreach (var | // ('var' is a TypeSyntax which is an expression syntax. var type = token.GetAncestors<TypeSyntax>().LastOrDefault(); if (type == null) { return true; } if (type.IsKind(SyntaxKind.GenericName) || type.IsKind(SyntaxKind.AliasQualifiedName) || type.IsKind(SyntaxKind.PredefinedType)) { return false; } ExpressionSyntax nameExpr = type; if (IsRightSideName(nameExpr)) { nameExpr = (ExpressionSyntax)nameExpr.Parent!; } // If this name is the start of a local variable declaration context, we // shouldn't show is or as. For example: for(var | if (syntaxTree.IsLocalVariableDeclarationContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), cancellationToken)) { return false; } // Not on the left hand side of an object initializer if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.IdentifierName) && (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression))) { return false; } // Not after an 'out' declaration expression. For example: M(out var | if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.IdentifierName)) { if (token.Parent.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { return false; } } if (token.Text == SyntaxFacts.GetText(SyntaxKind.AsyncKeyword)) { // async $$ // // 'async' will look like a normal identifier. But we don't want to follow it // with 'is' or 'as' or 'with' if it's actually the start of a lambda. var delegateType = CSharpTypeInferenceService.Instance.InferDelegateType( semanticModel, token.SpanStart, cancellationToken); if (delegateType != null) { return false; } } // Now, make sure the name was actually in a location valid for // an expression. If so, then we know we can follow it. if (syntaxTree.IsExpressionContext(nameExpr.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(nameExpr.SpanStart, cancellationToken), attributes: false, cancellationToken: cancellationToken)) { return true; } return false; } return false; } private static bool IsRightSideName(ExpressionSyntax name) { if (name.Parent != null) { switch (name.Parent.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)name.Parent).Right == name; case SyntaxKind.AliasQualifiedName: return ((AliasQualifiedNameSyntax)name.Parent).Name == name; case SyntaxKind.SimpleMemberAccessExpression: return ((MemberAccessExpressionSyntax)name.Parent).Name == name; } } return false; } public static bool IsCatchOrFinallyContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // try { // } | // try { // } c| // try { // } catch { // } | // try { // } catch { // } c| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.CloseBraceToken)) { var block = token.GetAncestor<BlockSyntax>(); if (block != null && token == block.GetLastToken(includeSkipped: true)) { if (block.IsParentKind(SyntaxKind.TryStatement) || block.IsParentKind(SyntaxKind.CatchClause)) { return true; } } } return false; } public static bool IsCatchFilterContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // catch | // catch i| // catch (declaration) | // catch (declaration) i| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CatchKeyword)) { return true; } if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CloseParenToken) && token.Parent.IsKind(SyntaxKind.CatchDeclaration)) { return true; } return false; } public static bool IsEnumBaseListContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Options: // enum E : | // enum E : i| return token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.BaseList) && token.Parent.IsParentKind(SyntaxKind.EnumDeclaration); } public static bool IsEnumTypeMemberAccessContext(this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var token = syntaxTree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.DotToken)) { return false; } SymbolInfo leftHandBinding; if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)token.Parent; leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken); } else if (token.Parent.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && token.Parent.IsParentKind(SyntaxKind.IsExpression, out BinaryExpressionSyntax? binaryExpression) && binaryExpression.Right == qualifiedName) { // The right-hand side of an is expression could be an enum leftHandBinding = semanticModel.GetSymbolInfo(qualifiedName.Left, cancellationToken); } else if (token.Parent.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName1) && token.Parent.IsParentKind(SyntaxKind.DeclarationPattern, out DeclarationPatternSyntax? declarationExpression) && declarationExpression.Type == qualifiedName1) { // The right-hand side of an is declaration expression could be an enum leftHandBinding = semanticModel.GetSymbolInfo(qualifiedName1.Left, cancellationToken); } else { return false; } var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault(); if (symbol == null) { return false; } switch (symbol.Kind) { case SymbolKind.NamedType: return ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Enum; case SymbolKind.Alias: var target = ((IAliasSymbol)symbol).Target; return target.IsType && ((ITypeSymbol)target).TypeKind == TypeKind.Enum; } return false; } public static bool IsFunctionPointerCallingConventionContext(this SyntaxTree syntaxTree, SyntaxToken targetToken) { return targetToken.IsKind(SyntaxKind.AsteriskToken) && targetToken.Parent is FunctionPointerTypeSyntax functionPointerType && targetToken == functionPointerType.AsteriskToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #pragma warning disable IDE0060 // Remove unused parameter - Majority of extension methods in this file have an unused 'SyntaxTree' this parameter for consistency with other Context related extension methods. namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal static partial class SyntaxTreeExtensions { public static bool IsAttributeNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); // cases: // [ | if (token.IsKind(SyntaxKind.OpenBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { return true; } // cases: // [Goo(1), | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { return true; } // cases: // [specifier: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.AttributeTargetSpecifier)) { return true; } // cases: // [Namespace.| if (token.Parent.IsKind(SyntaxKind.QualifiedName) && token.Parent.IsParentKind(SyntaxKind.Attribute)) { return true; } // cases: // [global::| if (token.Parent.IsKind(SyntaxKind.AliasQualifiedName) && token.Parent.IsParentKind(SyntaxKind.Attribute)) { return true; } return false; } public static bool IsGlobalMemberDeclarationContext( this SyntaxTree syntaxTree, int position, ISet<SyntaxKind> validModifiers, CancellationToken cancellationToken) { if (!syntaxTree.IsScript()) { return false; } var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); var parent = token.Parent; var modifierTokens = syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition); if (modifierTokens.IsEmpty()) { if (token.IsKind(SyntaxKind.CloseBracketToken) && parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && !IsGlobalAttributeList(attributeList)) { // Allow empty modifier tokens if we have an attribute list parent = attributeList.Parent; } else { return false; } } if (modifierTokens.IsSubsetOf(validModifiers)) { // the parent is the member // the grandparent is the container of the member // in interactive, it's possible that there might be an intervening "incomplete" member for partially // typed declarations that parse ambiguously. For example, "internal e". It's also possible for a // complete member to be parsed based on data after the caret, e.g. "unsafe $$ void L() { }". if (parent.IsKind(SyntaxKind.CompilationUnit) || (parent is MemberDeclarationSyntax && parent.IsParentKind(SyntaxKind.CompilationUnit))) { return true; } } return false; // Local functions static bool IsGlobalAttributeList(AttributeListSyntax attributeList) { if (attributeList.Target is { Identifier: { RawKind: var kind } }) { return kind == (int)SyntaxKind.AssemblyKeyword || kind == (int)SyntaxKind.ModuleKeyword; } return false; } } public static bool IsMemberDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // class C { // | // class C { // void Goo() { // } // | // class C { // int i; // | // class C { // [Goo] // | var originalToken = tokenOnLeftOfPosition; var token = originalToken; // If we're touching the right of an identifier, move back to // previous token. token = token.GetPreviousTokenIfTouchingWord(position); // class C { // | if (token.IsKind(SyntaxKind.OpenBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax) { return true; } } // class C { // int i; // | if (token.IsKind(SyntaxKind.SemicolonToken)) { if (token.Parent is MemberDeclarationSyntax && token.Parent.Parent is BaseTypeDeclarationSyntax) { return true; } } // class A { // class C {} // | // class C { // void Goo() { // } // | if (token.IsKind(SyntaxKind.CloseBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax && token.Parent.Parent is BaseTypeDeclarationSyntax) { // after a nested type return true; } else if (token.Parent is AccessorListSyntax) { // after a property return true; } else if ( token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { // after a method/operator/etc. return true; } } // namespace Goo { // [Bar] // | if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { // attributes belong to a member which itself is in a // container. // the parent is the attribute // the grandparent is the owner of the attribute // the great-grandparent is the container that the owner is in var container = token.Parent.Parent?.Parent; if (container is BaseTypeDeclarationSyntax) { return true; } } return false; } public static bool IsMemberDeclarationContext( this SyntaxTree syntaxTree, int position, CSharpSyntaxContext? contextOpt, ISet<SyntaxKind>? validModifiers, ISet<SyntaxKind>? validTypeDeclarations, bool canBePartial, CancellationToken cancellationToken) { var typeDecl = contextOpt != null ? contextOpt.ContainingTypeOrEnumDeclaration : syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken); if (typeDecl == null) { return false; } validTypeDeclarations ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (!validTypeDeclarations.Contains(typeDecl.Kind())) { return false; } // Check many of the simple cases first. var leftToken = contextOpt != null ? contextOpt.LeftToken : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = contextOpt != null ? contextOpt.TargetToken : leftToken.GetPreviousTokenIfTouchingWord(position); if (token.IsAnyAccessorDeclarationContext(position)) { return false; } if (syntaxTree.IsMemberDeclarationContext(position, leftToken)) { return true; } // A member can also show up after certain types of modifiers if (canBePartial && token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return true; } var modifierTokens = contextOpt != null ? contextOpt.PrecedingModifiers : syntaxTree.GetPrecedingModifiers(position, leftToken); if (modifierTokens.IsEmpty()) { return false; } validModifiers ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (modifierTokens.IsSubsetOf(validModifiers)) { var member = token.Parent; if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async", not followed by modifier: treat it as type if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token).Any(x => x == SyntaxKind.AsyncKeyword)) { return false; } // rule out async lambdas inside a method if (token.GetAncestor<StatementSyntax>() == null) { member = token.GetAncestor<MemberDeclarationSyntax>(); } } // cases: // public | // async | // public async | return member != null && member.Parent is BaseTypeDeclarationSyntax; } return false; } public static bool IsLambdaDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxKind otherModifier, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = leftToken.GetPreviousTokenIfTouchingWord(position); if (syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken)) { return true; } var modifierTokens = syntaxTree.GetPrecedingModifiers(position, token, out var beforeModifiersPosition); if (modifierTokens.Count == 1 && modifierTokens.Contains(otherModifier)) { if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async" not followed by modifier: treat as parameter name if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token).Contains(SyntaxKind.AsyncKeyword)) { return false; } } leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); return syntaxTree.IsExpressionContext(beforeModifiersPosition, token, attributes: false, cancellationToken); } return false; } public static bool IsLocalFunctionDeclarationContext( this SyntaxTree syntaxTree, int position, ISet<SyntaxKind> validModifiers, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var token = leftToken.GetPreviousTokenIfTouchingWord(position); // Local functions are always valid in a statement context. They are also valid for top-level statements (as // opposed to global functions which are defined in the global statement context of scripts). if (syntaxTree.IsStatementContext(position, leftToken, cancellationToken) || (!syntaxTree.IsScript() && syntaxTree.IsGlobalStatementContext(position, cancellationToken))) { return true; } // Also valid after certain modifiers var modifierTokens = syntaxTree.GetPrecedingModifiers( position, token, out var beforeModifiersPosition); if (modifierTokens.IsSubsetOf(validModifiers)) { if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { // second appearance of "async" not followed by modifier: treat as type if (syntaxTree.GetPrecedingModifiers(token.SpanStart, token) .Contains(SyntaxKind.AsyncKeyword)) { return false; } } leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); // If one or more attribute lists are present before the caret, check to see if those attribute lists // were written in a local function declaration context. while (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList)) { beforeModifiersPosition = attributeList.OpenBracketToken.SpanStart; leftToken = syntaxTree.FindTokenOnLeftOfPosition(beforeModifiersPosition, cancellationToken); token = leftToken.GetPreviousTokenIfTouchingWord(beforeModifiersPosition); } return syntaxTree.IsStatementContext(beforeModifiersPosition, token, cancellationToken) || (!syntaxTree.IsScript() && syntaxTree.IsGlobalStatementContext(beforeModifiersPosition, cancellationToken)); } return false; } public static bool IsTypeDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // root: | // extern alias a; // | // using Goo; // | // using Goo = Bar; // | // namespace N {} // | // namespace N { // | // class C {} // | // class C { // | // class C { // void Goo() { // } // | // class C { // int i; // | // class C { // [Goo] // | // (all the class cases apply to structs, interfaces and records). var originalToken = tokenOnLeftOfPosition; var token = originalToken; // If we're touching the right of an identifier, move back to // previous token. token = token.GetPreviousTokenIfTouchingWord(position); // a type decl can't come before usings/externs var nextToken = originalToken.GetNextToken(includeSkipped: true); if (nextToken.IsUsingOrExternKeyword() || (nextToken.Kind() == SyntaxKind.GlobalKeyword && nextToken.GetAncestor<UsingDirectiveSyntax>()?.GlobalKeyword == nextToken)) { return false; } // root: | if (token.IsKind(SyntaxKind.None)) { // root namespace // a type decl can't come before usings/externs if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit && (compilationUnit.Externs.Count > 0 || compilationUnit.Usings.Count > 0)) { return false; } return true; } if (token.IsKind(SyntaxKind.OpenBraceToken) && token.Parent is NamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; // extern alias a; // | // using Goo; // | // class C { // int i; // | // namespace NS; // | if (token.IsKind(SyntaxKind.SemicolonToken)) { if (token.Parent.IsKind(SyntaxKind.ExternAliasDirective, SyntaxKind.UsingDirective)) { return true; } else if (token.Parent is MemberDeclarationSyntax) { return true; } } // class C {} // | // namespace N {} // | // class C { // void Goo() { // } // | if (token.IsKind(SyntaxKind.CloseBraceToken)) { if (token.Parent is BaseTypeDeclarationSyntax) { return true; } else if (token.Parent.IsKind(SyntaxKind.NamespaceDeclaration)) { return true; } else if (token.Parent is AccessorListSyntax) { return true; } else if ( token.Parent.IsKind(SyntaxKind.Block) && token.Parent.Parent is MemberDeclarationSyntax) { return true; } } // namespace Goo { // [Bar] // | // namespace NS; // [Attr] // | if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList)) { // assembly attributes belong to the containing compilation unit if (token.Parent.IsParentKind(SyntaxKind.CompilationUnit)) return true; // other attributes belong to a member which itself is in a // container. // the parent is the attribute // the grandparent is the owner of the attribute // the great-grandparent is the container that the owner is in var container = token.Parent?.Parent?.Parent; if (container is CompilationUnitSyntax or BaseNamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; } return false; } public static bool IsTypeDeclarationContext( this SyntaxTree syntaxTree, int position, CSharpSyntaxContext? contextOpt, ISet<SyntaxKind>? validModifiers, ISet<SyntaxKind>? validTypeDeclarations, bool canBePartial, CancellationToken cancellationToken) { // We only allow nested types inside a class, struct, or interface, not inside a // an enum. var typeDecl = contextOpt != null ? contextOpt.ContainingTypeDeclaration : syntaxTree.GetContainingTypeDeclaration(position, cancellationToken); validTypeDeclarations ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (typeDecl != null) { if (!validTypeDeclarations.Contains(typeDecl.Kind())) { return false; } } // Check many of the simple cases first. var leftToken = contextOpt != null ? contextOpt.LeftToken : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); // If we're touching the right of an identifier, move back to // previous token. var token = contextOpt != null ? contextOpt.TargetToken : leftToken.GetPreviousTokenIfTouchingWord(position); if (token.IsAnyAccessorDeclarationContext(position)) { return false; } if (syntaxTree.IsTypeDeclarationContext(position, leftToken, cancellationToken)) { return true; } // A type can also show up after certain types of modifiers if (canBePartial && token.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword)) { return true; } // using static | is never a type declaration context if (token.IsStaticKeywordInUsingDirective()) { return false; } var modifierTokens = contextOpt != null ? contextOpt.PrecedingModifiers : syntaxTree.GetPrecedingModifiers(position, leftToken); if (modifierTokens.IsEmpty()) { return false; } validModifiers ??= SpecializedCollections.EmptySet<SyntaxKind>(); if (modifierTokens.IsProperSubsetOf(validModifiers)) { // the parent is the member // the grandparent is the container of the member var container = token.Parent?.Parent; // ref $$ // readonly ref $$ if (container.IsKind(SyntaxKind.IncompleteMember, out IncompleteMemberSyntax? incompleteMember)) return incompleteMember.Type.IsKind(SyntaxKind.RefType); if (container is CompilationUnitSyntax or NamespaceDeclarationSyntax or TypeDeclarationSyntax) return true; } return false; } public static bool IsNamespaceContext( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // first do quick exit check if (syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsRightOfDotOrArrow(position, cancellationToken)) { return false; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); // global:: if (token.IsKind(SyntaxKind.ColonColonToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.GlobalKeyword)) { return true; } // using | // but not: // using | = Bar // Note: we take care of the using alias case in the IsTypeContext // call below. if (token.IsKind(SyntaxKind.UsingKeyword)) { var usingDirective = token.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null) { if (token.GetNextToken(includeSkipped: true).Kind() != SyntaxKind.EqualsToken && usingDirective.Alias == null) { return true; } } } // using static | if (token.IsStaticKeywordInUsingDirective()) { return true; } // if it is not using directive location, most of places where // type can appear, namespace can appear as well return syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt); } public static bool IsNamespaceDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree.IsScript() || syntaxTree.IsInNonUserCode(position, cancellationToken)) return false; var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token == default) return false; var declaration = token.GetAncestor<BaseNamespaceDeclarationSyntax>(); if (declaration?.NamespaceKeyword == token) return true; return declaration?.Name.Span.IntersectsWith(position) == true; } public static bool IsPartialTypeDeclarationNameContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, [NotNullWhen(true)] out TypeDeclarationSyntax? declarationSyntax) { if (!syntaxTree.IsInNonUserCode(position, cancellationToken)) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if ((token.IsKind(SyntaxKind.ClassKeyword) || token.IsKind(SyntaxKind.StructKeyword) || token.IsKind(SyntaxKind.InterfaceKeyword)) && token.GetPreviousToken().IsKind(SyntaxKind.PartialKeyword)) { declarationSyntax = token.GetAncestor<TypeDeclarationSyntax>(); return declarationSyntax != null && declarationSyntax.Keyword == token; } } declarationSyntax = null; return false; } public static bool IsDefinitelyNotTypeContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsInNonUserCode(position, cancellationToken) || syntaxTree.IsRightOfDotOrArrow(position, cancellationToken); } public static bool IsTypeContext( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // first do quick exit check if (syntaxTree.IsDefinitelyNotTypeContext(position, cancellationToken)) { return false; } // okay, now it is a case where we can't use parse tree (valid or error recovery) to // determine whether it is a right place to put type. use lex based one Cyrus created. var tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.CaseKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.EventKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || syntaxTree.IsAttributeNameContext(position, cancellationToken) || syntaxTree.IsBaseClassOrInterfaceContext(position, cancellationToken) || syntaxTree.IsCatchVariableDeclarationContext(position, cancellationToken) || syntaxTree.IsDefiniteCastTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsDelegateReturnTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) || syntaxTree.IsPrimaryFunctionExpressionContext(position, tokenOnLeftOfPosition) || syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt) || syntaxTree.IsFunctionPointerTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsFixedVariableDeclarationContext(position, tokenOnLeftOfPosition) || syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsIsOrAsTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsLocalVariableDeclarationContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsObjectCreationTypeContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsParameterTypeContext(position, tokenOnLeftOfPosition) || syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsStatementContext(position, tokenOnLeftOfPosition, cancellationToken) || syntaxTree.IsGlobalStatementContext(position, cancellationToken) || syntaxTree.IsTypeParameterConstraintContext(position, tokenOnLeftOfPosition) || syntaxTree.IsUsingAliasContext(position, cancellationToken) || syntaxTree.IsUsingStaticContext(position, cancellationToken) || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || syntaxTree.IsPossibleTupleContext(tokenOnLeftOfPosition, position) || syntaxTree.IsMemberDeclarationContext( position, contextOpt: null, validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } public static bool IsBaseClassOrInterfaceContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // class C : | // class C : Bar, | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.ColonToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.BaseList)) { return true; } } return false; } public static bool IsUsingAliasContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // using Goo = | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.EqualsToken) && token.GetAncestor<UsingDirectiveSyntax>() != null) { return true; } return false; } public static bool IsUsingStaticContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // using static | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); return token.IsStaticKeywordInUsingDirective(); } public static bool IsTypeArgumentOfConstraintClause( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // cases: // where | // class Goo<T> : Object where | var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return true; } if (token.IsKind(SyntaxKind.IdentifierToken) && token.HasMatchingText(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.SimpleBaseType) && token.Parent.Parent.IsParentKind(SyntaxKind.BaseList)) { return true; } return false; } public static bool IsTypeParameterConstraintStartContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // where T : | var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.ColonToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IdentifierToken) && token.GetPreviousToken(includeSkipped: true).GetPreviousToken().IsKind(SyntaxKind.WhereKeyword)) { return true; } return false; } public static bool IsTypeParameterConstraintContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (syntaxTree.IsTypeParameterConstraintStartContext(position, tokenOnLeftOfPosition)) { return true; } var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Can't come after new() // // where T : | // where T : class, | // where T : struct, | // where T : Goo, | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TypeParameterConstraintClause, out TypeParameterConstraintClauseSyntax? constraintClause)) { // Check if there's a 'new()' constraint. If there isn't, or we're before it, then // this is a type parameter constraint context. var firstConstructorConstraint = constraintClause.Constraints.FirstOrDefault(t => t is ConstructorConstraintSyntax); if (firstConstructorConstraint == null || firstConstructorConstraint.SpanStart > token.Span.End) { return true; } } return false; } public static bool IsTypeOfExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.TypeOfExpression)) { return true; } return false; } public static bool IsDefaultExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.DefaultExpression)) { return true; } return false; } public static bool IsSizeOfExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.SizeOfExpression)) { return true; } return false; } public static bool IsFunctionPointerTypeArgumentContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.CommaToken: return token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList); } return token switch { // ref modifiers { Parent: { RawKind: (int)SyntaxKind.FunctionPointerParameter } } => true, // Regular type specifiers { Parent: TypeSyntax { Parent: { RawKind: (int)SyntaxKind.FunctionPointerParameter } } } => true, _ => false }; } public static bool IsGenericTypeArgumentContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // cases: // Goo<| // Goo<Bar,| // Goo<Bar<Baz<int[],| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() != SyntaxKind.LessThanToken && token.Kind() != SyntaxKind.CommaToken) { return false; } if (token.Parent is TypeArgumentListSyntax) { // Easy case, it was known to be a generic name, so this is a type argument context. return true; } if (!syntaxTree.IsInPartiallyWrittenGeneric(position, cancellationToken, out var nameToken)) { return false; } if (!(nameToken.Parent is NameSyntax name)) { return false; } // Looks viable! If they provided a binding, then check if it binds properly to // an actual generic entity. if (semanticModelOpt == null) { // No binding. Just make the decision based on the syntax tree. return true; } // '?' is syntactically ambiguous in incomplete top-level statements: // // T ? goo<| // // Might be an incomplete conditional expression or an incomplete declaration of a method returning a nullable type. // Bind T to see if it is a type. If it is we don't show signature help. if (name.IsParentKind(SyntaxKind.LessThanExpression) && name.Parent.IsParentKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax? conditional) && conditional.IsParentKind(SyntaxKind.ExpressionStatement) && conditional.Parent.IsParentKind(SyntaxKind.GlobalStatement)) { var conditionOrType = semanticModelOpt.GetSymbolInfo(conditional.Condition, cancellationToken); if (conditionOrType.GetBestOrAllSymbols().FirstOrDefault() is { Kind: SymbolKind.NamedType }) { return false; } } var symbols = semanticModelOpt.LookupName(nameToken, cancellationToken); return symbols.Any(s => { switch (s) { case INamedTypeSymbol nt: return nt.Arity > 0; case IMethodSymbol m: return m.Arity > 0; default: return false; } }); } public static bool IsParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, bool includeOperators, out int parameterIndex, out SyntaxKind previousModifier) { // cases: // Goo(| // Goo(int i, | // Goo([Bar]| var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); parameterIndex = -1; previousModifier = SyntaxKind.None; if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = 0; return true; } if (token.IsKind(SyntaxKind.LessThanToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList)) { parameterIndex = 0; return true; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ParameterList, out ParameterListSyntax? parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { var commaIndex = parameterList.Parameters.GetWithSeparators().IndexOf(token); parameterIndex = commaIndex / 2 + 1; return true; } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.FunctionPointerParameterList, out FunctionPointerParameterListSyntax? funcPtrParamList)) { var commaIndex = funcPtrParamList.Parameters.GetWithSeparators().IndexOf(token); parameterIndex = commaIndex / 2 + 1; return true; } if (token.IsKind(SyntaxKind.CloseBracketToken) && token.Parent.IsKind(SyntaxKind.AttributeList) && token.Parent.IsParentKind(SyntaxKind.Parameter, out ParameterSyntax? parameter) && parameter.IsParentKind(SyntaxKind.ParameterList, out parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = parameterList.Parameters.IndexOf(parameter); return true; } if (token.IsKind(SyntaxKind.RefKeyword, SyntaxKind.InKeyword, SyntaxKind.OutKeyword, SyntaxKind.ThisKeyword, SyntaxKind.ParamsKeyword) && token.Parent.IsKind(SyntaxKind.Parameter, out parameter) && parameter.IsParentKind(SyntaxKind.ParameterList, out parameterList) && parameterList.IsDelegateOrConstructorOrLocalFunctionOrMethodOrOperatorParameterList(includeOperators)) { parameterIndex = parameterList.Parameters.IndexOf(parameter); previousModifier = token.Kind(); return true; } return false; } public static bool IsParamsModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, includeOperators: false, out _, out var previousModifier) && previousModifier == SyntaxKind.None) { return true; } var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { return token.Parent.IsKind(SyntaxKind.BracketedParameterList); } return false; } public static bool IsDelegateReturnTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.DelegateKeyword) && token.Parent.IsKind(SyntaxKind.DelegateDeclaration)) { return true; } return false; } public static bool IsImplicitOrExplicitOperatorTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OperatorKeyword)) { if (token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ImplicitKeyword) || token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.ExplicitKeyword)) { return true; } } return false; } public static bool IsParameterTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (syntaxTree.IsParameterModifierContext(position, tokenOnLeftOfPosition, includeOperators: true, out _, out _)) { return true; } // int this[ | // int this[int i, | if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList)) { return true; } } return false; } public static bool IsPossibleExtensionMethodContext(this SyntaxTree syntaxTree, SyntaxToken tokenOnLeftOfPosition) { var method = tokenOnLeftOfPosition.Parent.GetAncestorOrThis<MethodDeclarationSyntax>(); var typeDecl = method.GetAncestorOrThis<TypeDeclarationSyntax>(); return method != null && typeDecl != null && typeDecl.IsKind(SyntaxKind.ClassDeclaration) && method.Modifiers.Any(SyntaxKind.StaticKeyword) && typeDecl.Modifiers.Any(SyntaxKind.StaticKeyword); } public static bool IsPossibleLambdaParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList) && token.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression)) { return true; } // TODO(cyrusn): Tie into semantic analysis system to only // consider this a lambda if this is a location where the // lambda's type would be inferred because of a delegate // or Expression<T> type. if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression) || token.Parent.IsKind(SyntaxKind.TupleExpression)) { return true; } } return false; } public static bool IsAnonymousMethodParameterModifierContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ParameterList) && token.Parent.IsParentKind(SyntaxKind.AnonymousMethodExpression)) { return true; } } return false; } public static bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword) || token.IsKind(SyntaxKind.OutKeyword)) { position = token.SpanStart; tokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); } if (IsAnonymousMethodParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition) || IsPossibleLambdaParameterModifierContext(syntaxTree, position, tokenOnLeftOfPosition)) { return true; } return false; } /// <summary> /// Are you possibly typing a tuple type or expression? /// This is used to suppress colon as a completion trigger (so that you can type element names). /// This is also used to recommend some keywords (like var). /// </summary> public static bool IsPossibleTupleContext(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // ($$ // (a, $$ if (IsPossibleTupleOpenParenOrComma(leftToken)) { return true; } // ((a, b) $$ // (..., (a, b) $$ if (leftToken.IsKind(SyntaxKind.CloseParenToken)) { if (leftToken.Parent.IsKind( SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.TupleType)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } } // (a $$ // (..., b $$ if (leftToken.IsKind(SyntaxKind.IdentifierToken)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent!); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } // (a.b $$ // (..., a.b $$ if (leftToken.IsKind(SyntaxKind.IdentifierToken) && leftToken.Parent.IsKind(SyntaxKind.IdentifierName) && leftToken.Parent.Parent.IsKind(SyntaxKind.QualifiedName, SyntaxKind.SimpleMemberAccessExpression)) { var possibleCommaOrParen = FindTokenOnLeftOfNode(leftToken.Parent.Parent); if (IsPossibleTupleOpenParenOrComma(possibleCommaOrParen)) { return true; } } return false; } public static bool IsAtStartOfPattern(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); if (leftToken.IsKind(SyntaxKind.OpenParenToken)) { if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenthesizedExpression)) { // If we're dealing with an expression surrounded by one or more sets of open parentheses, we need to // walk up the parens in order to see if we're actually at the start of a valid pattern or not. return IsAtStartOfPattern(syntaxTree, parenthesizedExpression.GetFirstToken().GetPreviousToken(), parenthesizedExpression.SpanStart); } // e is ((($$ 1 or 2))) if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedPattern)) { return true; } } // case $$ // is $$ if (leftToken.IsKind(SyntaxKind.CaseKeyword, SyntaxKind.IsKeyword)) { return true; } // e switch { $$ // e switch { ..., $$ if (leftToken.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.SwitchExpression)) { return true; } // e is ($$ // e is (..., $$ if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.PositionalPatternClause)) { return true; } // e is { P: $$ // e is { ..., P: $$ // e is { ..., P.P2: $$ if (leftToken.IsKind(SyntaxKind.ColonToken) && leftToken.Parent.IsKind(SyntaxKind.NameColon, SyntaxKind.ExpressionColon) && leftToken.Parent.IsParentKind(SyntaxKind.Subpattern)) { return true; } // e is 1 and $$ // e is 1 or $$ if (leftToken.IsKind(SyntaxKind.AndKeyword) || leftToken.IsKind(SyntaxKind.OrKeyword)) { return leftToken.Parent is BinaryPatternSyntax; } // e is not $$ if (leftToken.IsKind(SyntaxKind.NotKeyword) && leftToken.Parent.IsKind(SyntaxKind.NotPattern)) { return true; } return false; } public static bool IsAtEndOfPattern(this SyntaxTree syntaxTree, SyntaxToken leftToken, int position) { var originalLeftToken = leftToken; leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // For instance: // e is { A.$$ } if (leftToken.IsKind(SyntaxKind.DotToken)) { return false; } var patternSyntax = leftToken.GetAncestor<PatternSyntax>(); if (patternSyntax != null) { var lastTokenInPattern = patternSyntax.GetLastToken(); // This check should cover the majority of cases, e.g.: // e is 1 $$ // e is >= 0 $$ // e is { P: (1 $$ // e is { P: (1) $$ if (leftToken == lastTokenInPattern) { // Patterns such as 'e is not $$', 'e is 1 or $$', 'e is ($$', and 'e is null or global::$$' should be invalid here // as they are incomplete patterns. return !(leftToken.IsKind(SyntaxKind.OrKeyword) || leftToken.IsKind(SyntaxKind.AndKeyword) || leftToken.IsKind(SyntaxKind.NotKeyword) || leftToken.IsKind(SyntaxKind.OpenParenToken) || leftToken.IsKind(SyntaxKind.ColonColonToken)); } // We want to make sure that IsAtEndOfPattern returns true even when the user is in the middle of typing a keyword // after a pattern. // For example, with the keyword 'and', we want to make sure that 'e is int an$$' is still recognized as valid. if (lastTokenInPattern.Parent is SingleVariableDesignationSyntax variableDesignationSyntax && originalLeftToken.Parent == variableDesignationSyntax) { return patternSyntax is DeclarationPatternSyntax || patternSyntax is RecursivePatternSyntax; } } // e is C.P $$ // e is int $$ if (leftToken.IsLastTokenOfNode<TypeSyntax>(out var typeSyntax)) { // If typeSyntax is part of a qualified name, we want to get the fully-qualified name so that we can // later accurately perform the check comparing the right side of the BinaryExpressionSyntax to // the typeSyntax. while (typeSyntax.Parent is TypeSyntax parentTypeSyntax) { typeSyntax = parentTypeSyntax; } if (typeSyntax.Parent is BinaryExpressionSyntax binaryExpressionSyntax && binaryExpressionSyntax.OperatorToken.IsKind(SyntaxKind.IsKeyword) && binaryExpressionSyntax.Right == typeSyntax && !typeSyntax.IsVar) { return true; } } // We need to include a special case for switch statement cases, as some are not currently parsed as patterns, e.g. case (1 $$ if (IsAtEndOfSwitchStatementPattern(leftToken)) { return true; } return false; static bool IsAtEndOfSwitchStatementPattern(SyntaxToken leftToken) { SyntaxNode? node = leftToken.Parent as ExpressionSyntax; if (node == null) return false; // Walk up the right edge of all complete expressions. while (node is ExpressionSyntax && node.GetLastToken(includeZeroWidth: true) == leftToken) node = node.GetRequiredParent(); // Getting rid of the extra parentheses to deal with cases such as 'case (((1 $$' while (node is ParenthesizedExpressionSyntax) node = node.GetRequiredParent(); // case (1 $$ if (node is CaseSwitchLabelSyntax { Parent: SwitchSectionSyntax }) return true; return false; } } private static SyntaxToken FindTokenOnLeftOfNode(SyntaxNode node) => node.FindTokenOnLeftOfPosition(node.SpanStart); public static bool IsPossibleTupleOpenParenOrComma(this SyntaxToken possibleCommaOrParen) { if (!possibleCommaOrParen.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return false; } if (possibleCommaOrParen.Parent.IsKind( SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.TupleType, SyntaxKind.CastExpression)) { return true; } // in script if (possibleCommaOrParen.Parent.IsKind(SyntaxKind.ParameterList) && possibleCommaOrParen.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression, out ParenthesizedLambdaExpressionSyntax? parenthesizedLambda)) { if (parenthesizedLambda.ArrowToken.IsMissing) { return true; } } return false; } /// <summary> /// Are you possibly in the designation part of a deconstruction? /// This is used to enter suggestion mode (suggestions become soft-selected). /// </summary> public static bool IsPossibleDeconstructionDesignation(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); leftToken = leftToken.GetPreviousTokenIfTouchingWord(position); // The well-formed cases: // var ($$, y) = e; // (var $$, var y) = e; if (leftToken.Parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation) || leftToken.Parent.IsParentKind(SyntaxKind.ParenthesizedVariableDesignation)) { return true; } // (var $$, var y) // (var x, var y) if (syntaxTree.IsPossibleTupleContext(leftToken, position) && !IsPossibleTupleOpenParenOrComma(leftToken)) { return true; } // var ($$) // var (x, $$) if (IsPossibleVarDeconstructionOpenParenOrComma(leftToken)) { return true; } // var (($$), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken) && leftToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent))) { return true; } } // var ((x, $$), y) // var (($$, x), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.TupleExpression)) { if (IsPossibleVarDeconstructionOpenParenOrComma(FindTokenOnLeftOfNode(leftToken.Parent))) { return true; } } // foreach (var ($$ // foreach (var ((x, $$), y) if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { var outer = UnwrapPossibleTuple(leftToken.Parent!); if (outer.Parent.IsKind(SyntaxKind.ForEachStatement, out ForEachStatementSyntax? @foreach)) { if (@foreach.Expression == outer && @foreach.Type.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName) && identifierName.Identifier.ValueText == "var") { return true; } } } return false; } /// <summary> /// If inside a parenthesized or tuple expression, unwrap the nestings and return the container. /// </summary> private static SyntaxNode UnwrapPossibleTuple(SyntaxNode node) { while (true) { if (node.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { node = node.Parent; continue; } if (node.Parent.IsKind(SyntaxKind.Argument) && node.Parent.Parent.IsKind(SyntaxKind.TupleExpression)) { node = node.Parent.Parent; continue; } return node; } } private static bool IsPossibleVarDeconstructionOpenParenOrComma(SyntaxToken leftToken) { if (leftToken.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && leftToken.Parent.IsKind(SyntaxKind.ArgumentList) && leftToken.Parent.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation)) { if (invocation.Expression.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName) && identifierName.Identifier.ValueText == "var") { return true; } } return false; } public static bool HasNames(this TupleExpressionSyntax tuple) => tuple.Arguments.Any(a => a.NameColon != null); public static bool IsValidContextForFromClause( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { if (syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModelOpt) && !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition)) { return true; } // cases: // var q = | // var q = f| // // var q = from x in y // | // // var q = from x in y // f| // // this list is *not* exhaustive. // the first two are handled by 'IsExpressionContext' var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } public static bool IsValidContextForJoinClause( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } public static bool IsDeclarationExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // M(out var // var x = var var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OutKeyword) && token.Parent.IsKind(SyntaxKind.Argument)) { return true; } if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.EqualsValueClause) && token.Parent.IsParentKind(SyntaxKind.VariableDeclarator)) { return true; } return false; } public static bool IsLocalVariableDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // const var // out var // for (var // foreach (var // await foreach (var // using (var // await using (var // from var // join var var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); // const | if (token.IsKind(SyntaxKind.ConstKeyword) && token.Parent.IsKind(SyntaxKind.LocalDeclarationStatement)) { return true; } // ref | // ref readonly | // for ( ref | // foreach ( ref | x if (token.IsKind(SyntaxKind.RefKeyword, SyntaxKind.ReadOnlyKeyword)) { var parent = token.Parent; if (parent.IsKind(SyntaxKind.RefType, SyntaxKind.RefExpression, SyntaxKind.LocalDeclarationStatement)) { if (parent.IsParentKind(SyntaxKind.VariableDeclaration) && parent.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.ForStatement, SyntaxKind.ForEachVariableStatement)) { return true; } if (parent.IsParentKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement)) { return true; } } } // out | if (token.IsKind(SyntaxKind.OutKeyword) && token.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.RefKindKeyword == token) { return true; } if (token.IsKind(SyntaxKind.OpenParenToken)) { // for ( | // foreach ( | // await foreach ( | // using ( | // await using ( | var previous = token.GetPreviousToken(includeSkipped: true); if (previous.IsKind(SyntaxKind.ForKeyword) || previous.IsKind(SyntaxKind.ForEachKeyword) || previous.IsKind(SyntaxKind.UsingKeyword)) { return true; } } // from | var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken); if (token.IsKindOrHasMatchingText(SyntaxKind.FromKeyword) && syntaxTree.IsValidContextForFromClause(token.SpanStart, tokenOnLeftOfStart, cancellationToken)) { return true; } // join | if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.JoinKeyword) && syntaxTree.IsValidContextForJoinClause(token.SpanStart, tokenOnLeftOfStart)) { return true; } return false; } public static bool IsFixedVariableDeclarationContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // fixed (var var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.FixedKeyword)) { return true; } return false; } public static bool IsCatchVariableDeclarationContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // cases: // catch (var var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CatchKeyword)) { return true; } return false; } public static bool IsIsOrAsTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.IsKeyword) || token.IsKind(SyntaxKind.AsKeyword)) { return true; } return false; } public static bool IsObjectCreationTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.NewKeyword)) { // we can follow a 'new' if it's the 'new' for an expression. var start = token.SpanStart; var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken); return IsNonConstantExpressionContext(syntaxTree, token.SpanStart, tokenOnLeftOfStart, cancellationToken) || syntaxTree.IsStatementContext(token.SpanStart, tokenOnLeftOfStart, cancellationToken) || syntaxTree.IsGlobalStatementContext(token.SpanStart, cancellationToken); } return false; } private static bool IsNonConstantExpressionContext(SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { return syntaxTree.IsExpressionContext(position, tokenOnLeftOfPosition, attributes: true, cancellationToken: cancellationToken) && !syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition); } public static bool IsPreProcessorDirectiveContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var leftToken = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); return syntaxTree.IsPreProcessorDirectiveContext(position, leftToken, cancellationToken); } public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return IsPreProcessorKeywordContext( syntaxTree, position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true)); } public static bool IsPreProcessorKeywordContext(this SyntaxTree syntaxTree, int position, SyntaxToken preProcessorTokenOnLeftOfPosition) { // cases: // #| // #d| // # | // # d| // note: comments are not allowed between the # and item. var token = preProcessorTokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.HashToken)) { return true; } return false; } public static bool IsStatementContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { #if false // we're in a statement if the thing that comes before allows for // statements to follow. Or if we're on a just started identifier // in the first position where a statement can go. if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); return token.IsBeginningOfStatementContext(); } public static bool IsGlobalStatementContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { #if false if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.None)) { // global statements can't come before usings/externs if (syntaxTree.GetRoot(cancellationToken) is CompilationUnitSyntax compilationUnit && (compilationUnit.Externs.Count > 0 || compilationUnit.Usings.Count > 0)) { return false; } return true; } return token.IsBeginningOfGlobalStatementContext(); } public static bool IsInstanceContext(this SyntaxTree syntaxTree, SyntaxToken targetToken, SemanticModel semanticModel, CancellationToken cancellationToken) { #if false if (syntaxTree.IsInPreprocessorDirectiveContext(position, cancellationToken)) { return false; } #endif var enclosingSymbol = semanticModel.GetEnclosingSymbol(targetToken.SpanStart, cancellationToken); while (enclosingSymbol is IMethodSymbol method && (method.MethodKind == MethodKind.LocalFunction || method.MethodKind == MethodKind.AnonymousFunction)) { if (method.IsStatic) { return false; } // It is allowed to reference the instance (`this`) within a local function or anonymous function, as long as the containing method allows it enclosingSymbol = enclosingSymbol.ContainingSymbol; } return enclosingSymbol is { IsStatic: false }; } public static bool IsPossibleCastTypeContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.OpenParenToken) && syntaxTree.IsExpressionContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), false, cancellationToken)) { return true; } return false; } public static bool IsDefiniteCastTypeContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.CastExpression)) { return true; } return false; } public static bool IsConstantExpressionContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { if (IsAtStartOfPattern(syntaxTree, tokenOnLeftOfPosition, position)) { return true; } var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); // goto case | if (token.IsKind(SyntaxKind.CaseKeyword) && token.Parent.IsKind(SyntaxKind.GotoCaseStatement)) { return true; } if (token.IsKind(SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue)) { if (equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) && equalsValue.Parent.IsParentKind(SyntaxKind.VariableDeclaration)) { // class C { const int i = | var fieldDeclaration = equalsValue.GetAncestor<FieldDeclarationSyntax>(); if (fieldDeclaration != null) { return fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword); } // void M() { const int i = | var localDeclaration = equalsValue.GetAncestor<LocalDeclarationStatementSyntax>(); if (localDeclaration != null) { return localDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword); } } // enum E { A = | if (equalsValue.IsParentKind(SyntaxKind.EnumMemberDeclaration)) { return true; } // void M(int i = | if (equalsValue.IsParentKind(SyntaxKind.Parameter)) { return true; } } // [Goo( | // [Goo(x, | if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList) && (token.IsKind(SyntaxKind.CommaToken) || token.IsKind(SyntaxKind.OpenParenToken))) { return true; } // [Goo(x: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.NameColon) && token.Parent.IsParentKind(SyntaxKind.AttributeArgument)) { return true; } // [Goo(X = | if (token.IsKind(SyntaxKind.EqualsToken) && token.Parent.IsKind(SyntaxKind.NameEquals) && token.Parent.IsParentKind(SyntaxKind.AttributeArgument)) { return true; } // TODO: Fixed-size buffer declarations return false; } public static bool IsLabelContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var gotoStatement = token.GetAncestor<GotoStatementSyntax>(); if (gotoStatement != null) { if (gotoStatement.GotoKeyword == token) { return true; } if (gotoStatement.Expression != null && !gotoStatement.Expression.IsMissing && gotoStatement.Expression is IdentifierNameSyntax && ((IdentifierNameSyntax)gotoStatement.Expression).Identifier == token && token.IntersectsWith(position)) { return true; } } return false; } public static bool IsExpressionContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition, bool attributes, CancellationToken cancellationToken, SemanticModel? semanticModelOpt = null) { // cases: // var q = | // var q = a| // this list is *not* exhaustive. var token = tokenOnLeftOfPosition.GetPreviousTokenIfTouchingWord(position); if (token.GetAncestor<ConditionalDirectiveTriviaSyntax>() != null) { return false; } if (!attributes) { if (token.GetAncestor<AttributeListSyntax>() != null) { return false; } } if (syntaxTree.IsConstantExpressionContext(position, tokenOnLeftOfPosition)) { return true; } // no expressions after . :: -> if (token.IsKind(SyntaxKind.DotToken) || token.IsKind(SyntaxKind.ColonColonToken) || token.IsKind(SyntaxKind.MinusGreaterThanToken)) { return false; } // Normally you can have any sort of expression after an equals. However, this does not // apply to a "using Goo = ..." situation. if (token.IsKind(SyntaxKind.EqualsToken)) { if (token.Parent.IsKind(SyntaxKind.NameEquals) && token.Parent.IsParentKind(SyntaxKind.UsingDirective)) { return false; } } // q = | // q -= | // q *= | // q += | // q /= | // q ^= | // q %= | // q &= | // q |= | // q <<= | // q >>= | // q ??= | if (token.IsKind(SyntaxKind.EqualsToken) || token.IsKind(SyntaxKind.MinusEqualsToken) || token.IsKind(SyntaxKind.AsteriskEqualsToken) || token.IsKind(SyntaxKind.PlusEqualsToken) || token.IsKind(SyntaxKind.SlashEqualsToken) || token.IsKind(SyntaxKind.ExclamationEqualsToken) || token.IsKind(SyntaxKind.CaretEqualsToken) || token.IsKind(SyntaxKind.AmpersandEqualsToken) || token.IsKind(SyntaxKind.BarEqualsToken) || token.IsKind(SyntaxKind.PercentEqualsToken) || token.IsKind(SyntaxKind.LessThanLessThanEqualsToken) || token.IsKind(SyntaxKind.GreaterThanGreaterThanEqualsToken) || token.IsKind(SyntaxKind.QuestionQuestionEqualsToken)) { return true; } // ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) { return true; } // - | // + | // ~ | // ! | if (token.Parent is PrefixUnaryExpressionSyntax prefix) { return prefix.OperatorToken == token; } // not sure about these: // ++ | // -- | #if false token.Kind == SyntaxKind.PlusPlusToken || token.Kind == SyntaxKind.DashDashToken) #endif // await | if (token.Parent is AwaitExpressionSyntax awaitExpression) { return awaitExpression.AwaitKeyword == token; } // Check for binary operators. // Note: // - We handle < specially as it can be ambiguous with generics. // - We handle * specially because it can be ambiguous with pointer types. // a * // a / // a % // a + // a - // a << // a >> // a < // a > // a && // a || // a & // a | // a ^ if (token.Parent is BinaryExpressionSyntax binary) { // If the client provided a binding, then check if this is actually generic. If so, // then this is not an expression context. i.e. if we have "Goo < |" then it could // be an expression context, or it could be a type context if Goo binds to a type or // method. if (semanticModelOpt != null && syntaxTree.IsGenericTypeArgumentContext(position, tokenOnLeftOfPosition, cancellationToken, semanticModelOpt)) { return false; } if (binary.OperatorToken == token) { // If this is a multiplication expression and a semantic model was passed in, // check to see if the expression to the left is a type name. If it is, treat // this as a pointer type. if (token.IsKind(SyntaxKind.AsteriskToken) && semanticModelOpt != null) { if (binary.Left is TypeSyntax type && type.IsPotentialTypeName(semanticModelOpt, cancellationToken)) { return false; } } return true; } } // Special case: // Goo * bar // Goo ? bar // This parses as a local decl called bar of type Goo* or Goo? if (tokenOnLeftOfPosition.IntersectsWith(position) && tokenOnLeftOfPosition.IsKind(SyntaxKind.IdentifierToken)) { var previousToken = tokenOnLeftOfPosition.GetPreviousToken(includeSkipped: true); if (previousToken.IsKind(SyntaxKind.AsteriskToken) || previousToken.IsKind(SyntaxKind.QuestionToken)) { if (previousToken.Parent.IsKind(SyntaxKind.PointerType) || previousToken.Parent.IsKind(SyntaxKind.NullableType)) { var type = previousToken.Parent as TypeSyntax; if (type.IsParentKind(SyntaxKind.VariableDeclaration) && type.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? declStatement)) { // note, this doesn't apply for cases where we know it // absolutely is not multiplication or a conditional expression. var underlyingType = type is PointerTypeSyntax pointerType ? pointerType.ElementType : ((NullableTypeSyntax)type).ElementType; if (!underlyingType.IsPotentialTypeName(semanticModelOpt, cancellationToken)) { return true; } } } } } // new int[| // new int[expr, | if (token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ArrayRankSpecifier)) { return true; } } // goo ? | if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent.IsKind(SyntaxKind.ConditionalExpression, out ConditionalExpressionSyntax? conditionalExpression)) { // If the condition is simply a TypeSyntax that binds to a type, treat this as a nullable type. return !(conditionalExpression.Condition is TypeSyntax type) || !type.IsPotentialTypeName(semanticModelOpt, cancellationToken); } // goo ? bar : | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.ConditionalExpression)) { return true; } // typeof(| // default(| // sizeof(| if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.TypeOfExpression, SyntaxKind.DefaultExpression, SyntaxKind.SizeOfExpression)) { return false; } } // var(| // var(id, | // Those are more likely to be deconstruction-declarations being typed than invocations a method "var" if (token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) && token.IsInvocationOfVarExpression()) { return false; } // Goo(| // Goo(expr, | // this[| // var t = (1, | // var t = (| , 2) if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.OpenBracketToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList, SyntaxKind.TupleExpression)) { return true; } } // [Goo(| // [Goo(expr, | if (attributes) { if (token.IsKind(SyntaxKind.OpenParenToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.AttributeArgumentList)) { return true; } } } // Goo(ref | // Goo(in | // Goo(out | // ref var x = ref | if (token.IsKind(SyntaxKind.RefKeyword) || token.IsKind(SyntaxKind.InKeyword) || token.IsKind(SyntaxKind.OutKeyword)) { if (token.Parent.IsKind(SyntaxKind.Argument)) { return true; } else if (token.Parent.IsKind(SyntaxKind.RefExpression)) { // ( ref | // parenthesized expressions can't directly contain RefExpression, unless the user is typing an incomplete lambda expression. if (token.Parent.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return false; } return true; } } // Goo(bar: | if (token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.NameColon) && token.Parent.IsParentKind(SyntaxKind.Argument)) { return true; } // a => | if (token.IsKind(SyntaxKind.EqualsGreaterThanToken)) { return true; } // new List<int> { | // new List<int> { expr, | if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent is InitializerExpressionSyntax) { // The compiler treats the ambiguous case as an object initializer, so we'll say // expressions are legal here if (token.Parent.IsKind(SyntaxKind.ObjectInitializerExpression) && token.IsKind(SyntaxKind.OpenBraceToken)) { // In this position { a$$ =, the user is trying to type an object initializer. if (!token.IntersectsWith(position) && token.GetNextToken().GetNextToken().IsKind(SyntaxKind.EqualsToken)) { return false; } return true; } // Perform a semantic check to determine whether or not the type being created // can support a collection initializer. If not, this must be an object initializer // and can't be an expression context. if (semanticModelOpt != null && token.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation)) { var containingSymbol = semanticModelOpt.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (semanticModelOpt.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol is ITypeSymbol type && !type.CanSupportCollectionInitializer(containingSymbol)) { return false; } } return true; } } // for (; | // for (; ; | if (token.IsKind(SyntaxKind.SemicolonToken) && token.Parent.IsKind(SyntaxKind.ForStatement, out ForStatementSyntax? forStatement)) { if (token == forStatement.FirstSemicolonToken || token == forStatement.SecondSemicolonToken) { return true; } } // for ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ForStatement, out forStatement) && token == forStatement.OpenParenToken) { return true; } // for (; ; Goo(), | // for ( Goo(), | if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.ForStatement)) { return true; } // foreach (var v in | // await foreach (var v in | // from a in | // join b in | if (token.IsKind(SyntaxKind.InKeyword)) { if (token.Parent.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.ForEachVariableStatement, SyntaxKind.FromClause, SyntaxKind.JoinClause)) { return true; } } // join x in y on | // join x in y on a equals | if (token.IsKind(SyntaxKind.OnKeyword) || token.IsKind(SyntaxKind.EqualsKeyword)) { if (token.Parent.IsKind(SyntaxKind.JoinClause)) { return true; } } // where | if (token.IsKind(SyntaxKind.WhereKeyword) && token.Parent.IsKind(SyntaxKind.WhereClause)) { return true; } // orderby | // orderby a, | if (token.IsKind(SyntaxKind.OrderByKeyword) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } } // select | if (token.IsKind(SyntaxKind.SelectKeyword) && token.Parent.IsKind(SyntaxKind.SelectClause)) { return true; } // group | // group expr by | if (token.IsKind(SyntaxKind.GroupKeyword) || token.IsKind(SyntaxKind.ByKeyword)) { if (token.Parent.IsKind(SyntaxKind.GroupClause)) { return true; } } // return | // yield return | // but not: [return | if (token.IsKind(SyntaxKind.ReturnKeyword)) { if (token.GetPreviousToken(includeSkipped: true).Kind() != SyntaxKind.OpenBracketToken) { return true; } } // throw | if (token.IsKind(SyntaxKind.ThrowKeyword)) { return true; } // while ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhileKeyword)) { return true; } // todo: handle 'for' cases. // using ( | // await using ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.UsingStatement)) { return true; } // lock ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.LockKeyword)) { return true; } // lock ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.IfKeyword)) { return true; } // switch ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.SwitchKeyword)) { return true; } // checked ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.CheckedKeyword)) { return true; } // unchecked ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.UncheckedKeyword)) { return true; } // when ( | if (token.IsKind(SyntaxKind.OpenParenToken) && token.GetPreviousToken(includeSkipped: true).IsKind(SyntaxKind.WhenKeyword)) { return true; } // case ... when | if (token.IsKind(SyntaxKind.WhenKeyword) && token.Parent.IsKind(SyntaxKind.WhenClause)) { return true; } // (SomeType) | if (token.IsAfterPossibleCast()) { return true; } // In anonymous type initializer. // // new { | We allow new inside of anonymous object member declarators, so that the user // can dot into a member afterward. For example: // // var a = new { new C().Goo }; if (token.IsKind(SyntaxKind.OpenBraceToken) || token.IsKind(SyntaxKind.CommaToken)) { if (token.Parent.IsKind(SyntaxKind.AnonymousObjectCreationExpression)) { return true; } } // $"{ | // $@"{ | // $"{x} { | // $@"{x} { | if (token.IsKind(SyntaxKind.OpenBraceToken)) { return token.Parent.IsKind(SyntaxKind.Interpolation, out InterpolationSyntax? interpolation) && interpolation.OpenBraceToken == token; } return false; } public static bool IsInvocationOfVarExpression(this SyntaxToken token) => token.Parent.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax? invocation) && invocation.Expression.ToString() == "var"; public static bool IsNameOfContext(this SyntaxTree syntaxTree, int position, SemanticModel? semanticModelOpt = null, CancellationToken cancellationToken = default) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); // nameof(Goo.| // nameof(Goo.Bar.| // Locate the open paren. if (token.IsKind(SyntaxKind.DotToken)) { // Could have been parsed as member access if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var parentMemberAccess = token.Parent; while (parentMemberAccess.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { parentMemberAccess = parentMemberAccess.Parent; } if (parentMemberAccess.Parent.IsKind(SyntaxKind.Argument) && parentMemberAccess.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault())) { token = ((ArgumentListSyntax)parentMemberAccess.Parent.Parent!).OpenParenToken; } } // Could have been parsed as a qualified name. if (token.Parent.IsKind(SyntaxKind.QualifiedName)) { var parentQualifiedName = token.Parent; while (parentQualifiedName.Parent.IsKind(SyntaxKind.QualifiedName)) { parentQualifiedName = parentQualifiedName.Parent; } if (parentQualifiedName.Parent.IsKind(SyntaxKind.Argument) && parentQualifiedName.Parent.IsChildNode<ArgumentListSyntax>(a => a.Arguments.FirstOrDefault())) { token = ((ArgumentListSyntax)parentQualifiedName.Parent.Parent!).OpenParenToken; } } } ExpressionSyntax? parentExpression = null; // if the nameof expression has a missing close paren, it is parsed as an invocation expression. if (token.Parent.IsKind(SyntaxKind.ArgumentList) && token.Parent.Parent is InvocationExpressionSyntax invocationExpression && invocationExpression.IsNameOfInvocation()) { parentExpression = invocationExpression; } if (parentExpression != null) { if (semanticModelOpt == null) { return true; } return semanticModelOpt.GetSymbolInfo(parentExpression, cancellationToken).Symbol == null; } return false; } public static bool IsIsOrAsOrSwitchOrWithExpressionContext( this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, SyntaxToken tokenOnLeftOfPosition, CancellationToken cancellationToken) { // cases: // expr | var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Not if the position is a numeric literal if (token.IsKind(SyntaxKind.NumericLiteralToken)) { return false; } if (token.GetAncestor<BlockSyntax>() == null && token.GetAncestor<ArrowExpressionClauseSyntax>() == null) { return false; } // is/as/with are valid after expressions. if (token.IsLastTokenOfNode<ExpressionSyntax>(out var expression)) { // 'is/as/with' not allowed after a anonymous-method/lambda/method-group. if (expression.IsAnyLambdaOrAnonymousMethod()) return false; var symbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (symbol is IMethodSymbol) return false; // However, many names look like expressions. For example: // foreach (var | // ('var' is a TypeSyntax which is an expression syntax. var type = token.GetAncestors<TypeSyntax>().LastOrDefault(); if (type == null) { return true; } if (type.IsKind(SyntaxKind.GenericName) || type.IsKind(SyntaxKind.AliasQualifiedName) || type.IsKind(SyntaxKind.PredefinedType)) { return false; } ExpressionSyntax nameExpr = type; if (IsRightSideName(nameExpr)) { nameExpr = (ExpressionSyntax)nameExpr.Parent!; } // If this name is the start of a local variable declaration context, we // shouldn't show is or as. For example: for(var | if (syntaxTree.IsLocalVariableDeclarationContext(token.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(token.SpanStart, cancellationToken), cancellationToken)) { return false; } // Not on the left hand side of an object initializer if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.IdentifierName) && (token.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression) || token.Parent.IsParentKind(SyntaxKind.CollectionInitializerExpression))) { return false; } // Not after an 'out' declaration expression. For example: M(out var | if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.IdentifierName)) { if (token.Parent.IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) && argument.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword)) { return false; } } if (token.Text == SyntaxFacts.GetText(SyntaxKind.AsyncKeyword)) { // async $$ // // 'async' will look like a normal identifier. But we don't want to follow it // with 'is' or 'as' or 'with' if it's actually the start of a lambda. var delegateType = CSharpTypeInferenceService.Instance.InferDelegateType( semanticModel, token.SpanStart, cancellationToken); if (delegateType != null) { return false; } } // Now, make sure the name was actually in a location valid for // an expression. If so, then we know we can follow it. if (syntaxTree.IsExpressionContext(nameExpr.SpanStart, syntaxTree.FindTokenOnLeftOfPosition(nameExpr.SpanStart, cancellationToken), attributes: false, cancellationToken: cancellationToken)) { return true; } return false; } return false; } private static bool IsRightSideName(ExpressionSyntax name) { if (name.Parent != null) { switch (name.Parent.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)name.Parent).Right == name; case SyntaxKind.AliasQualifiedName: return ((AliasQualifiedNameSyntax)name.Parent).Name == name; case SyntaxKind.SimpleMemberAccessExpression: return ((MemberAccessExpressionSyntax)name.Parent).Name == name; } } return false; } public static bool IsCatchOrFinallyContext( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // try { // } | // try { // } c| // try { // } catch { // } | // try { // } catch { // } c| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (token.IsKind(SyntaxKind.CloseBraceToken)) { var block = token.GetAncestor<BlockSyntax>(); if (block != null && token == block.GetLastToken(includeSkipped: true)) { if (block.IsParentKind(SyntaxKind.TryStatement) || block.IsParentKind(SyntaxKind.CatchClause)) { return true; } } } return false; } public static bool IsCatchFilterContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { // cases: // catch | // catch i| // catch (declaration) | // catch (declaration) i| var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CatchKeyword)) { return true; } if (CodeAnalysis.CSharpExtensions.IsKind(token, SyntaxKind.CloseParenToken) && token.Parent.IsKind(SyntaxKind.CatchDeclaration)) { return true; } return false; } public static bool IsEnumBaseListContext(this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); // Options: // enum E : | // enum E : i| return token.IsKind(SyntaxKind.ColonToken) && token.Parent.IsKind(SyntaxKind.BaseList) && token.Parent.IsParentKind(SyntaxKind.EnumDeclaration); } public static bool IsEnumTypeMemberAccessContext(this SyntaxTree syntaxTree, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var token = syntaxTree .FindTokenOnLeftOfPosition(position, cancellationToken) .GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.DotToken)) { return false; } SymbolInfo leftHandBinding; if (token.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)token.Parent; leftHandBinding = semanticModel.GetSymbolInfo(memberAccess.Expression, cancellationToken); } else if (token.Parent.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName) && token.Parent.IsParentKind(SyntaxKind.IsExpression, out BinaryExpressionSyntax? binaryExpression) && binaryExpression.Right == qualifiedName) { // The right-hand side of an is expression could be an enum leftHandBinding = semanticModel.GetSymbolInfo(qualifiedName.Left, cancellationToken); } else if (token.Parent.IsKind(SyntaxKind.QualifiedName, out QualifiedNameSyntax? qualifiedName1) && token.Parent.IsParentKind(SyntaxKind.DeclarationPattern, out DeclarationPatternSyntax? declarationExpression) && declarationExpression.Type == qualifiedName1) { // The right-hand side of an is declaration expression could be an enum leftHandBinding = semanticModel.GetSymbolInfo(qualifiedName1.Left, cancellationToken); } else { return false; } var symbol = leftHandBinding.GetBestOrAllSymbols().FirstOrDefault(); if (symbol == null) { return false; } switch (symbol.Kind) { case SymbolKind.NamedType: return ((INamedTypeSymbol)symbol).TypeKind == TypeKind.Enum; case SymbolKind.Alias: var target = ((IAliasSymbol)symbol).Target; return target.IsType && ((ITypeSymbol)target).TypeKind == TypeKind.Enum; } return false; } public static bool IsFunctionPointerCallingConventionContext(this SyntaxTree syntaxTree, SyntaxToken targetToken) { return targetToken.IsKind(SyntaxKind.AsteriskToken) && targetToken.Parent is FunctionPointerTypeSyntax functionPointerType && targetToken == functionPointerType.AsteriskToken; } } }
1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedStringHashFunctionSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated synthesized method symbol /// representing string switch hash function /// </summary> internal sealed partial class SynthesizedStringSwitchHashMethod : SynthesizedGlobalMethodSymbol { internal SynthesizedStringSwitchHashMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, TypeSymbol paramType) : base(containingModule, privateImplType, returnType, PrivateImplementationDetails.SynthesizedStringHashFunctionName) { this.SetParameters(ImmutableArray.Create<ParameterSymbol>(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(paramType), 0, RefKind.None, "s"))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGen; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated synthesized method symbol /// representing string switch hash function /// </summary> internal sealed partial class SynthesizedStringSwitchHashMethod : SynthesizedGlobalMethodSymbol { internal SynthesizedStringSwitchHashMethod(SourceModuleSymbol containingModule, PrivateImplementationDetails privateImplType, TypeSymbol returnType, TypeSymbol paramType) : base(containingModule, privateImplType, returnType, PrivateImplementationDetails.SynthesizedStringHashFunctionName) { this.SetParameters(ImmutableArray.Create<ParameterSymbol>(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(paramType), 0, RefKind.None, "s"))); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Text/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Text { public static partial class Extensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => TextBufferContainer.From(buffer); public static ITextBuffer GetTextBuffer(this SourceTextContainer textContainer) => TryGetTextBuffer(textContainer) ?? throw new ArgumentException(TextEditorResources.textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer, nameof(textContainer)); public static ITextBuffer? TryGetTextBuffer(this SourceTextContainer? textContainer) => (textContainer as TextBufferContainer)?.TryFindEditorTextBuffer(); /// <summary> /// Returns the <see cref="ITextSnapshot"/> behind this <see cref="SourceText"/>, or null if it wasn't created from one. /// /// Note that multiple <see cref="ITextSnapshot"/>s may map to the same <see cref="SourceText"/> instance if it's /// <see cref="ITextVersion.ReiteratedVersionNumber" /> doesn't change. /// </summary> /// <returns>The underlying ITextSnapshot.</returns> public static ITextSnapshot? FindCorrespondingEditorTextSnapshot(this SourceText? text) => (text as SnapshotSourceText)?.TryFindEditorSnapshot(); internal static ITextImage? TryFindCorrespondingEditorTextImage(this SourceText? text) => (text as SnapshotSourceText)?.TextImage; internal static TextLine AsTextLine(this ITextSnapshotLine line) => line.Snapshot.AsText().Lines[line.LineNumber]; public static SourceText AsText(this ITextSnapshot textSnapshot) { textSnapshot.TextBuffer.Properties.TryGetProperty<ITextBufferCloneService>(typeof(ITextBufferCloneService), out var textBufferCloneServiceOpt); return SnapshotSourceText.From(textBufferCloneServiceOpt, textSnapshot); } internal static SourceText AsRoslynText(this ITextSnapshot textSnapshot, ITextBufferCloneService textBufferCloneServiceOpt, Encoding? encoding) => new SnapshotSourceText.ClosedSnapshotSourceText(textBufferCloneServiceOpt, ((ITextSnapshot2)textSnapshot).TextImage, encoding); /// <summary> /// Gets the workspace corresponding to the text buffer. /// </summary> public static Workspace? GetWorkspace(this ITextBuffer buffer) { var container = buffer.AsTextContainer(); if (Workspace.TryGetWorkspace(container, out var workspace)) { return workspace; } return null; } /// <summary> /// Gets the <see cref="Document"/>s from the corresponding <see cref="Workspace.CurrentSolution"/> that are associated with the <see cref="ITextSnapshot"/>'s buffer, /// updated to contain the same text as the snapshot if necessary. There may be multiple <see cref="Document"/>s associated with the buffer /// if the file is linked into multiple projects or is part of a Shared Project. /// </summary> public static IEnumerable<Document> GetRelatedDocumentsWithChanges(this ITextSnapshot text) => text.AsText().GetRelatedDocumentsWithChanges(); /// <summary> /// Gets the <see cref="Document"/> from the corresponding <see cref="Workspace.CurrentSolution"/> that is associated with the <see cref="ITextSnapshot"/>'s buffer /// in its current project context, updated to contain the same text as the snapshot if necessary. There may be multiple <see cref="Document"/>s /// associated with the buffer if it is linked into multiple projects or is part of a Shared Project. In this case, the <see cref="Workspace"/> /// is responsible for keeping track of which of these <see cref="Document"/>s is in the current project context. /// </summary> public static Document? GetOpenDocumentInCurrentContextWithChanges(this ITextSnapshot text) => text.AsText().GetOpenDocumentInCurrentContextWithChanges(); /// <summary> /// Gets the <see cref="Document"/>s from the corresponding <see cref="Workspace.CurrentSolution"/> that are associated with the <see cref="ITextBuffer"/>. /// There may be multiple <see cref="Document"/>s associated with the buffer if it is linked into multiple projects or is part of a Shared Project. /// </summary> public static IEnumerable<Document> GetRelatedDocuments(this ITextBuffer buffer) => buffer.AsTextContainer().GetRelatedDocuments(); internal static bool CanApplyChangeDocumentToWorkspace(this ITextBuffer buffer) => Workspace.TryGetWorkspace(buffer.AsTextContainer(), out var workspace) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument); /// <summary> /// Get the encoding used to load this <see cref="ITextBuffer"/> if possible. /// <para> /// Note that this will return <see cref="Encoding.UTF8"/> if the <see cref="ITextBuffer"/> /// didn't come from an <see cref="ITextDocument"/>, or if the <see cref="ITextDocument"/> /// is already closed. /// </para> /// </summary> internal static Encoding GetEncodingOrUTF8(this ITextBuffer textBuffer) => textBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDocument) ? textDocument.Encoding : Encoding.UTF8; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Threading; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Text { public static partial class Extensions { public static SourceTextContainer AsTextContainer(this ITextBuffer buffer) => TextBufferContainer.From(buffer); public static ITextBuffer GetTextBuffer(this SourceTextContainer textContainer) => TryGetTextBuffer(textContainer) ?? throw new ArgumentException(TextEditorResources.textContainer_is_not_a_SourceTextContainer_that_was_created_from_an_ITextBuffer, nameof(textContainer)); public static ITextBuffer? TryGetTextBuffer(this SourceTextContainer? textContainer) => (textContainer as TextBufferContainer)?.TryFindEditorTextBuffer(); /// <summary> /// Returns the <see cref="ITextSnapshot"/> behind this <see cref="SourceText"/>, or null if it wasn't created from one. /// /// Note that multiple <see cref="ITextSnapshot"/>s may map to the same <see cref="SourceText"/> instance if it's /// <see cref="ITextVersion.ReiteratedVersionNumber" /> doesn't change. /// </summary> /// <returns>The underlying ITextSnapshot.</returns> public static ITextSnapshot? FindCorrespondingEditorTextSnapshot(this SourceText? text) => (text as SnapshotSourceText)?.TryFindEditorSnapshot(); internal static ITextImage? TryFindCorrespondingEditorTextImage(this SourceText? text) => (text as SnapshotSourceText)?.TextImage; internal static TextLine AsTextLine(this ITextSnapshotLine line) => line.Snapshot.AsText().Lines[line.LineNumber]; public static SourceText AsText(this ITextSnapshot textSnapshot) { textSnapshot.TextBuffer.Properties.TryGetProperty<ITextBufferCloneService>(typeof(ITextBufferCloneService), out var textBufferCloneServiceOpt); return SnapshotSourceText.From(textBufferCloneServiceOpt, textSnapshot); } internal static SourceText AsRoslynText(this ITextSnapshot textSnapshot, ITextBufferCloneService textBufferCloneServiceOpt, Encoding? encoding) => new SnapshotSourceText.ClosedSnapshotSourceText(textBufferCloneServiceOpt, ((ITextSnapshot2)textSnapshot).TextImage, encoding); /// <summary> /// Gets the workspace corresponding to the text buffer. /// </summary> public static Workspace? GetWorkspace(this ITextBuffer buffer) { var container = buffer.AsTextContainer(); if (Workspace.TryGetWorkspace(container, out var workspace)) { return workspace; } return null; } /// <summary> /// Gets the <see cref="Document"/>s from the corresponding <see cref="Workspace.CurrentSolution"/> that are associated with the <see cref="ITextSnapshot"/>'s buffer, /// updated to contain the same text as the snapshot if necessary. There may be multiple <see cref="Document"/>s associated with the buffer /// if the file is linked into multiple projects or is part of a Shared Project. /// </summary> public static IEnumerable<Document> GetRelatedDocumentsWithChanges(this ITextSnapshot text) => text.AsText().GetRelatedDocumentsWithChanges(); /// <summary> /// Gets the <see cref="Document"/> from the corresponding <see cref="Workspace.CurrentSolution"/> that is associated with the <see cref="ITextSnapshot"/>'s buffer /// in its current project context, updated to contain the same text as the snapshot if necessary. There may be multiple <see cref="Document"/>s /// associated with the buffer if it is linked into multiple projects or is part of a Shared Project. In this case, the <see cref="Workspace"/> /// is responsible for keeping track of which of these <see cref="Document"/>s is in the current project context. /// </summary> public static Document? GetOpenDocumentInCurrentContextWithChanges(this ITextSnapshot text) => text.AsText().GetOpenDocumentInCurrentContextWithChanges(); /// <summary> /// Gets the <see cref="Document"/>s from the corresponding <see cref="Workspace.CurrentSolution"/> that are associated with the <see cref="ITextBuffer"/>. /// There may be multiple <see cref="Document"/>s associated with the buffer if it is linked into multiple projects or is part of a Shared Project. /// </summary> public static IEnumerable<Document> GetRelatedDocuments(this ITextBuffer buffer) => buffer.AsTextContainer().GetRelatedDocuments(); internal static bool CanApplyChangeDocumentToWorkspace(this ITextBuffer buffer) => Workspace.TryGetWorkspace(buffer.AsTextContainer(), out var workspace) && workspace.CanApplyChange(ApplyChangesKind.ChangeDocument); /// <summary> /// Get the encoding used to load this <see cref="ITextBuffer"/> if possible. /// <para> /// Note that this will return <see cref="Encoding.UTF8"/> if the <see cref="ITextBuffer"/> /// didn't come from an <see cref="ITextDocument"/>, or if the <see cref="ITextDocument"/> /// is already closed. /// </para> /// </summary> internal static Encoding GetEncodingOrUTF8(this ITextBuffer textBuffer) => textBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDocument) ? textDocument.Encoding : Encoding.UTF8; } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Compilation.EmitStreamProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public abstract partial class Compilation { /// <summary> /// Abstraction that allows the caller to delay the creation of the <see cref="Stream"/> values /// until they are actually needed. /// </summary> internal abstract class EmitStreamProvider { /// <summary> /// Returns an existing open stream or null if no stream has been open. /// </summary> public abstract Stream? Stream { get; } /// <summary> /// This method will be called once during Emit at the time the Compilation needs /// to create a stream for writing. It will not be called in the case of /// user errors in code. Shall not be called when <see cref="Stream"/> returns non-null. /// </summary> protected abstract Stream? CreateStream(DiagnosticBag diagnostics); /// <summary> /// Returns a <see cref="Stream"/>. If one cannot be gotten or created then a diagnostic will /// be added to <paramref name="diagnostics"/> /// </summary> public Stream? GetOrCreateStream(DiagnosticBag diagnostics) { return Stream ?? CreateStream(diagnostics); } } internal sealed class SimpleEmitStreamProvider : EmitStreamProvider { private readonly Stream _stream; internal SimpleEmitStreamProvider(Stream stream) { RoslynDebug.Assert(stream != null); _stream = stream; } public override Stream Stream => _stream; protected override Stream CreateStream(DiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public abstract partial class Compilation { /// <summary> /// Abstraction that allows the caller to delay the creation of the <see cref="Stream"/> values /// until they are actually needed. /// </summary> internal abstract class EmitStreamProvider { /// <summary> /// Returns an existing open stream or null if no stream has been open. /// </summary> public abstract Stream? Stream { get; } /// <summary> /// This method will be called once during Emit at the time the Compilation needs /// to create a stream for writing. It will not be called in the case of /// user errors in code. Shall not be called when <see cref="Stream"/> returns non-null. /// </summary> protected abstract Stream? CreateStream(DiagnosticBag diagnostics); /// <summary> /// Returns a <see cref="Stream"/>. If one cannot be gotten or created then a diagnostic will /// be added to <paramref name="diagnostics"/> /// </summary> public Stream? GetOrCreateStream(DiagnosticBag diagnostics) { return Stream ?? CreateStream(diagnostics); } } internal sealed class SimpleEmitStreamProvider : EmitStreamProvider { private readonly Stream _stream; internal SimpleEmitStreamProvider(Stream stream) { RoslynDebug.Assert(stream != null); _stream = stream; } public override Stream Stream => _stream; protected override Stream CreateStream(DiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Composition; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; #if CODE_STYLE using System.Diagnostics; using System.IO; #else using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { [UseExportProvider] public abstract partial class AbstractCodeActionOrUserDiagnosticTest { public struct TestParameters { internal readonly OptionsCollection options; internal readonly TestHost testHost; internal readonly string workspaceKind; internal readonly object fixProviderData; internal readonly ParseOptions parseOptions; internal readonly CompilationOptions compilationOptions; internal readonly int index; internal readonly CodeActionPriority? priority; internal readonly bool retainNonFixableDiagnostics; internal readonly bool includeDiagnosticsOutsideSelection; internal readonly string title; internal TestParameters( ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, OptionsCollection options = null, object fixProviderData = null, int index = 0, CodeActionPriority? priority = null, bool retainNonFixableDiagnostics = false, bool includeDiagnosticsOutsideSelection = false, string title = null, TestHost testHost = TestHost.InProcess, string workspaceKind = null) { this.parseOptions = parseOptions; this.compilationOptions = compilationOptions; this.options = options; this.fixProviderData = fixProviderData; this.index = index; this.priority = priority; this.retainNonFixableDiagnostics = retainNonFixableDiagnostics; this.includeDiagnosticsOutsideSelection = includeDiagnosticsOutsideSelection; this.title = title; this.testHost = testHost; this.workspaceKind = workspaceKind; } public TestParameters WithParseOptions(ParseOptions parseOptions) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithCompilationOptions(CompilationOptions compilationOptions) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); internal TestParameters WithOptions(OptionsCollection options) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithFixProviderData(object fixProviderData) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithIndex(int index) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithRetainNonFixableDiagnostics(bool retainNonFixableDiagnostics) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithIncludeDiagnosticsOutsideSelection(bool includeDiagnosticsOutsideSelection) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithWorkspaceKind(string workspaceKind) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); } #pragma warning disable IDE0052 // Remove unread private members (unused when CODE_STYLE is set) private readonly ITestOutputHelper _logger; #pragma warning restore protected AbstractCodeActionOrUserDiagnosticTest(ITestOutputHelper logger = null) { _logger = logger; } private const string AutoGeneratedAnalyzerConfigHeader = @"# auto-generated .editorconfig for code style options"; protected internal abstract string GetLanguage(); protected ParenthesesOptionsProvider ParenthesesOptionsProvider => new ParenthesesOptionsProvider(this.GetLanguage()); protected abstract ParseOptions GetScriptOptions(); private protected virtual IDocumentServiceProvider GetDocumentServiceProvider() => null; protected virtual TestComposition GetComposition() => EditorTestCompositions.EditorFeatures .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); protected virtual void InitializeWorkspace(TestWorkspace workspace, TestParameters parameters) { } protected virtual TestParameters SetParameterDefaults(TestParameters parameters) => parameters; protected TestWorkspace CreateWorkspaceFromOptions(string workspaceMarkupOrCode, TestParameters parameters) { var composition = GetComposition().WithTestHostParts(parameters.testHost); parameters = SetParameterDefaults(parameters); var documentServiceProvider = GetDocumentServiceProvider(); var workspace = TestWorkspace.IsWorkspaceElement(workspaceMarkupOrCode) ? TestWorkspace.Create(XElement.Parse(workspaceMarkupOrCode), openDocuments: false, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind) : TestWorkspace.Create(GetLanguage(), parameters.compilationOptions, parameters.parseOptions, files: new[] { workspaceMarkupOrCode }, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind); #if !CODE_STYLE if (parameters.testHost == TestHost.OutOfProcess && _logger != null) { var remoteHostProvider = (InProcRemoteHostClientProvider)workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); remoteHostProvider.TraceListener = new XunitTraceListener(_logger); } #endif InitializeWorkspace(workspace, parameters); // For CodeStyle layer testing, we create an .editorconfig at project root // to apply the options as workspace options are not available in CodeStyle layer. // Otherwise, we apply the options directly to the workspace. #if CODE_STYLE // We need to ensure that our projects/documents are rooted for // execution from CodeStyle layer as we will be adding a rooted .editorconfig to each project // to apply the options. if (parameters.options != null) { MakeProjectsAndDocumentsRooted(workspace); AddAnalyzerConfigDocumentWithOptions(workspace, parameters.options); } #else workspace.ApplyOptions(parameters.options); #endif return workspace; } #if CODE_STYLE private static void MakeProjectsAndDocumentsRooted(TestWorkspace workspace) { const string defaultRootFilePath = @"z:\"; var newSolution = workspace.CurrentSolution; foreach (var projectId in workspace.CurrentSolution.ProjectIds) { var project = newSolution.GetProject(projectId); string projectRootFilePath; if (!PathUtilities.IsAbsolute(project.FilePath)) { projectRootFilePath = defaultRootFilePath; newSolution = newSolution.WithProjectFilePath(projectId, Path.Combine(projectRootFilePath, project.FilePath)); } else { projectRootFilePath = PathUtilities.GetPathRoot(project.FilePath); } foreach (var documentId in project.DocumentIds) { var document = newSolution.GetDocument(documentId); if (!PathUtilities.IsAbsolute(document.FilePath)) { newSolution = newSolution.WithDocumentFilePath(documentId, Path.Combine(projectRootFilePath, document.FilePath)); } else { Assert.Equal(projectRootFilePath, PathUtilities.GetPathRoot(document.FilePath)); } } } var applied = workspace.TryApplyChanges(newSolution); Assert.True(applied); return; } private static void AddAnalyzerConfigDocumentWithOptions(TestWorkspace workspace, OptionsCollection options) { Debug.Assert(options != null); var analyzerConfigText = GenerateAnalyzerConfigText(options); var newSolution = workspace.CurrentSolution; foreach (var project in workspace.Projects) { Assert.True(PathUtilities.IsAbsolute(project.FilePath)); var projectRootFilePath = PathUtilities.GetPathRoot(project.FilePath); var documentId = DocumentId.CreateNewId(project.Id); newSolution = newSolution.AddAnalyzerConfigDocument( documentId, ".editorconfig", SourceText.From(analyzerConfigText), filePath: Path.Combine(projectRootFilePath, ".editorconfig")); } var applied = workspace.TryApplyChanges(newSolution); Assert.True(applied); return; string GenerateAnalyzerConfigText(OptionsCollection options) { var textBuilder = new StringBuilder(); // Add an auto-generated header at the top so we can skip this file in expected baseline validation. textBuilder.AppendLine(AutoGeneratedAnalyzerConfigHeader); textBuilder.AppendLine(); textBuilder.AppendLine(options.GetEditorConfigText()); return textBuilder.ToString(); } } #endif private static TestParameters WithRegularOptions(TestParameters parameters) => parameters.WithParseOptions(parameters.parseOptions?.WithKind(SourceCodeKind.Regular)); private TestParameters WithScriptOptions(TestParameters parameters) => parameters.WithParseOptions(parameters.parseOptions?.WithKind(SourceCodeKind.Script) ?? GetScriptOptions()); protected async Task TestMissingInRegularAndScriptAsync( string initialMarkup, TestParameters parameters = default, int codeActionIndex = 0) { await TestMissingAsync(initialMarkup, WithRegularOptions(parameters), codeActionIndex); await TestMissingAsync(initialMarkup, WithScriptOptions(parameters), codeActionIndex); } protected async Task TestMissingAsync( string initialMarkup, TestParameters parameters = default, int codeActionIndex = 0) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var offeredActions = Environment.NewLine + string.Join(Environment.NewLine, actions.Select(action => action.Title)); if (codeActionIndex == 0) { Assert.True(actions.Length == 0, "An action was offered when none was expected. Offered actions:" + offeredActions); } else { Assert.True(actions.Length <= codeActionIndex, "An action was offered at the specified index when none was expected. Offered actions:" + offeredActions); } } } protected async Task TestDiagnosticMissingAsync( string initialMarkup, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var diagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters); Assert.True(0 == diagnostics.Length, $"Expected no diagnostics, but got {diagnostics.Length}"); } } protected abstract Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters); protected abstract Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync( TestWorkspace workspace, TestParameters parameters); protected Task TestSmartTagTextAsync(string initialMarkup, string displayText, int index) => TestSmartTagTextAsync(initialMarkup, displayText, new TestParameters(index: index)); protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<string> glyphTags, int index) => TestSmartTagGlyphTagsAsync(initialMarkup, glyphTags, new TestParameters(index: index)); protected async Task TestSmartTagTextAsync( string initialMarkup, string displayText, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(displayText, action.Title); } } protected async Task TestSmartTagGlyphTagsAsync( string initialMarkup, ImmutableArray<string> glyph, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(glyph, action.Tags); } } protected async Task TestExactActionSetOfferedAsync( string initialMarkup, IEnumerable<string> expectedActionSet, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var actualActionSet = actions.Select(a => a.Title); Assert.True(actualActionSet.SequenceEqual(expectedActionSet), "Expected: " + string.Join(", ", expectedActionSet) + "\nActual: " + string.Join(", ", actualActionSet)); } } protected async Task TestActionCountAsync( string initialMarkup, int count, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(count, actions.Length); } } internal Task TestInRegularAndScriptAsync( string initialMarkup, string expectedMarkup, int index = 0, CodeActionPriority? priority = null, CompilationOptions compilationOptions = null, OptionsCollection options = null, object fixProviderData = null, ParseOptions parseOptions = null, string title = null, TestHost testHost = TestHost.InProcess) { return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, title: title, testHost: testHost)); } internal Task TestInRegularAndScript1Async( string initialMarkup, string expectedMarkup, int index = 0, TestParameters parameters = default) { return TestInRegularAndScript1Async(initialMarkup, expectedMarkup, parameters.WithIndex(index)); } internal async Task TestInRegularAndScript1Async( string initialMarkup, string expectedMarkup, TestParameters parameters) { await TestAsync(initialMarkup, expectedMarkup, WithRegularOptions(parameters)); // VB scripting is not supported: if (GetLanguage() == LanguageNames.CSharp) { await TestAsync(initialMarkup, expectedMarkup, WithScriptOptions(parameters)); } } internal Task TestAsync( string initialMarkup, string expectedMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions = null, int index = 0, OptionsCollection options = null, object fixProviderData = null, CodeActionPriority? priority = null, TestHost testHost = TestHost.InProcess) { return TestAsync( initialMarkup, expectedMarkup, new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, testHost: testHost)); } private async Task TestAsync( string initialMarkup, string expectedMarkup, TestParameters parameters) { MarkupTestFile.GetSpans( initialMarkup.NormalizeLineEndings(), out var initialMarkupWithoutSpans, out IDictionary<string, ImmutableArray<TextSpan>> initialSpanMap); const string UnnecessaryMarkupKey = "Unnecessary"; var unnecessarySpans = initialSpanMap.GetOrAdd(UnnecessaryMarkupKey, _ => ImmutableArray<TextSpan>.Empty); MarkupTestFile.GetSpans( expectedMarkup.NormalizeLineEndings(), out var expected, out IDictionary<string, ImmutableArray<TextSpan>> expectedSpanMap); var conflictSpans = expectedSpanMap.GetOrAdd("Conflict", _ => ImmutableArray<TextSpan>.Empty); var renameSpans = expectedSpanMap.GetOrAdd("Rename", _ => ImmutableArray<TextSpan>.Empty); var warningSpans = expectedSpanMap.GetOrAdd("Warning", _ => ImmutableArray<TextSpan>.Empty); var navigationSpans = expectedSpanMap.GetOrAdd("Navigation", _ => ImmutableArray<TextSpan>.Empty); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { // Ideally this check would always run, but there are several hundred tests that would need to be // updated with {|Unnecessary:|} spans. if (unnecessarySpans.Any()) { var allDiagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters .WithRetainNonFixableDiagnostics(true) .WithIncludeDiagnosticsOutsideSelection(true)); TestUnnecessarySpans(allDiagnostics, unnecessarySpans, UnnecessaryMarkupKey, initialMarkupWithoutSpans); } var (_, action) = await GetCodeActionsAsync(workspace, parameters); await TestActionAsync( workspace, expected, action, conflictSpans, renameSpans, warningSpans, navigationSpans, parameters); } } private static void TestUnnecessarySpans( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<TextSpan> expectedSpans, string markupKey, string initialMarkupWithoutSpans) { var unnecessaryLocations = diagnostics.SelectMany(GetUnnecessaryLocations) .OrderBy(location => location.SourceSpan.Start) .ThenBy(location => location.SourceSpan.End) .ToArray(); if (expectedSpans.Length != unnecessaryLocations.Length) { AssertEx.Fail(BuildFailureMessage(expectedSpans, WellKnownDiagnosticTags.Unnecessary, markupKey, initialMarkupWithoutSpans, diagnostics)); } for (var i = 0; i < expectedSpans.Length; i++) { var actual = unnecessaryLocations[i].SourceSpan; var expected = expectedSpans[i]; Assert.Equal(expected, actual); } static IEnumerable<Location> GetUnnecessaryLocations(Diagnostic diagnostic) { if (diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) yield return diagnostic.Location; if (!diagnostic.Properties.TryGetValue(WellKnownDiagnosticTags.Unnecessary, out var additionalUnnecessaryLocationsString)) yield break; var locations = JArray.Parse(additionalUnnecessaryLocationsString); foreach (var locationIndex in locations) yield return diagnostic.AdditionalLocations[(int)locationIndex]; } } private static string BuildFailureMessage( ImmutableArray<TextSpan> expectedSpans, string diagnosticTag, string markupKey, string initialMarkupWithoutSpans, ImmutableArray<Diagnostic> diagnosticsWithTag) { var message = $"Expected {expectedSpans.Length} diagnostic spans with custom tag '{diagnosticTag}', but there were {diagnosticsWithTag.Length}."; if (expectedSpans.Length == 0) { message += $" If a diagnostic span tagged '{diagnosticTag}' is expected, surround the span in the test markup with the following syntax: {{|Unnecessary:...}}"; var segments = new List<(int originalStringIndex, string segment)>(); foreach (var diagnostic in diagnosticsWithTag) { var documentOffset = initialMarkupWithoutSpans.IndexOf(diagnosticsWithTag.First().Location.SourceTree.ToString()); if (documentOffset == -1) continue; segments.Add((documentOffset + diagnostic.Location.SourceSpan.Start, "{|" + markupKey + ":")); segments.Add((documentOffset + diagnostic.Location.SourceSpan.End, "|}")); } if (segments.Any()) { message += Environment.NewLine + "Example:" + Environment.NewLine + Environment.NewLine + InsertSegments(initialMarkupWithoutSpans, segments); } } return message; } private static string InsertSegments(string originalString, IEnumerable<(int originalStringIndex, string segment)> segments) { var builder = new StringBuilder(); var positionInOriginalString = 0; foreach (var (originalStringIndex, segment) in segments.OrderBy(s => s.originalStringIndex)) { builder.Append(originalString, positionInOriginalString, originalStringIndex - positionInOriginalString); builder.Append(segment); positionInOriginalString = originalStringIndex; } builder.Append(originalString, positionInOriginalString, originalString.Length - positionInOriginalString); return builder.ToString(); } internal async Task<Tuple<Solution, Solution>> TestActionAsync( TestWorkspace workspace, string expected, CodeAction action, ImmutableArray<TextSpan> conflictSpans, ImmutableArray<TextSpan> renameSpans, ImmutableArray<TextSpan> warningSpans, ImmutableArray<TextSpan> navigationSpans, TestParameters parameters) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, parameters); return await TestOperationsAsync( workspace, expected, operations, conflictSpans, renameSpans, warningSpans, navigationSpans, expectedChangedDocumentId: null); } protected static async Task<Tuple<Solution, Solution>> TestOperationsAsync( TestWorkspace workspace, string expectedText, ImmutableArray<CodeActionOperation> operations, ImmutableArray<TextSpan> conflictSpans, ImmutableArray<TextSpan> renameSpans, ImmutableArray<TextSpan> warningSpans, ImmutableArray<TextSpan> navigationSpans, DocumentId expectedChangedDocumentId) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; if (TestWorkspace.IsWorkspaceElement(expectedText)) { var newSolutionWithLinkedFiles = await newSolution.WithMergedLinkedFileChangesAsync(oldSolution); await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolutionWithLinkedFiles, workspace.ExportProvider); return Tuple.Create(oldSolution, newSolution); } var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution); var fixedRoot = await document.GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); // To help when a user just writes a test (and supplied no 'expectedText') just print // out the entire 'actualText' (without any trimming). in the case that we have both, // call the normal AssertEx helper which will print out a good diff. if (expectedText == "") { Assert.Equal((object)expectedText, actualText); } else { AssertEx.EqualOrDiff(expectedText, actualText); } TestAnnotations(conflictSpans, ConflictAnnotation.Kind); TestAnnotations(renameSpans, RenameAnnotation.Kind); TestAnnotations(warningSpans, WarningAnnotation.Kind); TestAnnotations(navigationSpans, NavigationAnnotation.Kind); return Tuple.Create(oldSolution, newSolution); void TestAnnotations(ImmutableArray<TextSpan> expectedSpans, string annotationKind) { var annotatedItems = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).OrderBy(s => s.SpanStart).ToList(); Assert.True(expectedSpans.Length == annotatedItems.Count, $"Annotations of kind '{annotationKind}' didn't match. Expected: {expectedSpans.Length}. Actual: {annotatedItems.Count}."); for (var i = 0; i < Math.Min(expectedSpans.Length, annotatedItems.Count); i++) { var actual = annotatedItems[i].Span; var expected = expectedSpans[i]; Assert.Equal(expected, actual); } } } protected static Document GetDocumentToVerify(DocumentId expectedChangedDocumentId, Solution oldSolution, Solution newSolution) { Document document; // If the expectedChangedDocumentId is not mentioned then we expect only single document to be changed if (expectedChangedDocumentId == null) { var projectDifferences = SolutionUtilities.GetSingleChangedProjectChanges(oldSolution, newSolution); var documentId = projectDifferences.GetChangedDocuments().FirstOrDefault() ?? projectDifferences.GetAddedDocuments().FirstOrDefault(); Assert.NotNull(documentId); document = newSolution.GetDocument(documentId); } else { // This method obtains only the document changed and does not check the project state. document = newSolution.GetDocument(expectedChangedDocumentId); } return document; } private static async Task VerifyAgainstWorkspaceDefinitionAsync(string expectedText, Solution newSolution, ExportProvider exportProvider) { using (var expectedWorkspace = TestWorkspace.Create(expectedText, exportProvider: exportProvider)) { var expectedSolution = expectedWorkspace.CurrentSolution; Assert.Equal(expectedSolution.Projects.Count(), newSolution.Projects.Count()); foreach (var project in newSolution.Projects) { var expectedProject = expectedSolution.GetProjectsByName(project.Name).Single(); Assert.Equal(expectedProject.Documents.Count(), project.Documents.Count()); foreach (var doc in project.Documents) { var root = await doc.GetSyntaxRootAsync(); var expectedDocuments = expectedProject.Documents.Where(d => d.Name == doc.Name); if (expectedDocuments.Any()) { Assert.Single(expectedDocuments); } else { AssertEx.Fail($"Could not find document with name '{doc.Name}'"); } var expectedDocument = expectedDocuments.Single(); var expectedRoot = await expectedDocument.GetSyntaxRootAsync(); VerifyExpectedDocumentText(expectedRoot.ToFullString(), root.ToFullString()); } foreach (var additionalDoc in project.AdditionalDocuments) { var root = await additionalDoc.GetTextAsync(); var expectedDocument = expectedProject.AdditionalDocuments.Single(d => d.Name == additionalDoc.Name); var expectedRoot = await expectedDocument.GetTextAsync(); VerifyExpectedDocumentText(expectedRoot.ToString(), root.ToString()); } foreach (var analyzerConfigDoc in project.AnalyzerConfigDocuments) { var root = await analyzerConfigDoc.GetTextAsync(); var actualString = root.ToString(); if (actualString.StartsWith(AutoGeneratedAnalyzerConfigHeader)) { // Skip validation for analyzer config file that is auto-generated by test framework // for applying code style options. continue; } var expectedDocument = expectedProject.AnalyzerConfigDocuments.Single(d => d.FilePath == analyzerConfigDoc.FilePath); var expectedRoot = await expectedDocument.GetTextAsync(); VerifyExpectedDocumentText(expectedRoot.ToString(), actualString); } } } return; // Local functions. static void VerifyExpectedDocumentText(string expected, string actual) { if (expected == "") { Assert.Equal((object)expected, actual); } else { Assert.Equal(expected, actual); } } } internal async Task<ImmutableArray<CodeActionOperation>> VerifyActionAndGetOperationsAsync( TestWorkspace workspace, CodeAction action, TestParameters parameters) { if (action is null) { var diagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters.WithRetainNonFixableDiagnostics(true)); throw new Exception("No action was offered when one was expected. Diagnostics from the compilation: " + string.Join("", diagnostics.Select(d => Environment.NewLine + d.ToString()))); } if (parameters.priority != null) { Assert.Equal(parameters.priority.Value, action.Priority); } if (parameters.title != null) { Assert.Equal(parameters.title, action.Title); } return await action.GetOperationsAsync(CancellationToken.None); } protected static Tuple<Solution, Solution> ApplyOperationsAndGetSolution( TestWorkspace workspace, IEnumerable<CodeActionOperation> operations) { Tuple<Solution, Solution> result = null; foreach (var operation in operations) { if (operation is ApplyChangesOperation && result == null) { var oldSolution = workspace.CurrentSolution; var newSolution = ((ApplyChangesOperation)operation).ChangedSolution; result = Tuple.Create(oldSolution, newSolution); } else if (operation.ApplyDuringTests) { var oldSolution = workspace.CurrentSolution; operation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); var newSolution = workspace.CurrentSolution; result = Tuple.Create(oldSolution, newSolution); } } if (result == null) { throw new InvalidOperationException("No ApplyChangesOperation found"); } return result; } protected virtual ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => actions; internal static void VerifyCodeActionsRegisteredByProvider(CodeFixProvider provider, List<CodeFix> fixes) { if (provider.GetFixAllProvider() == null) { // Only require unique equivalence keys when the fixer supports FixAll return; } var diagnosticsAndEquivalenceKeyToTitleMap = new Dictionary<(Diagnostic diagnostic, string equivalenceKey), string>(); foreach (var fix in fixes) { VerifyCodeAction(fix.Action, fix.Diagnostics, provider, diagnosticsAndEquivalenceKeyToTitleMap); } return; static void VerifyCodeAction( CodeAction codeAction, ImmutableArray<Diagnostic> diagnostics, CodeFixProvider provider, Dictionary<(Diagnostic diagnostic, string equivalenceKey), string> diagnosticsAndEquivalenceKeyToTitleMap) { if (!codeAction.NestedCodeActions.IsEmpty) { // Only validate leaf code actions. foreach (var nestedAction in codeAction.NestedCodeActions) { VerifyCodeAction(nestedAction, diagnostics, provider, diagnosticsAndEquivalenceKeyToTitleMap); } return; } foreach (var diagnostic in diagnostics) { var key = (diagnostic, codeAction.EquivalenceKey); var existingTitle = diagnosticsAndEquivalenceKeyToTitleMap.GetOrAdd(key, _ => codeAction.Title); if (existingTitle != codeAction.Title) { var messageSuffix = codeAction.EquivalenceKey != null ? string.Empty : @" Consider using the title as the equivalence key instead of 'null'"; Assert.False(true, @$"Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: - Name: '{provider.GetType().Name}' - Title 1: '{codeAction.Title}' - Title 2: '{existingTitle}' - Shared equivalence key: '{codeAction.EquivalenceKey ?? "<null>"}'{messageSuffix}"); } } } } protected static ImmutableArray<CodeAction> FlattenActions(ImmutableArray<CodeAction> codeActions) { return codeActions.SelectMany(a => a.NestedCodeActions.Length > 0 ? a.NestedCodeActions : ImmutableArray.Create(a)).ToImmutableArray(); } protected static ImmutableArray<CodeAction> GetNestedActions(ImmutableArray<CodeAction> codeActions) => codeActions.SelectMany(a => a.NestedCodeActions).ToImmutableArray(); /// <summary> /// Tests all the code actions for the given <paramref name="input"/> string. Each code /// action must produce the corresponding output in the <paramref name="outputs"/> array. /// /// Will throw if there are more outputs than code actions or more code actions than outputs. /// </summary> protected Task TestAllInRegularAndScriptAsync( string input, params string[] outputs) { return TestAllInRegularAndScriptAsync(input, parameters: default, outputs); } protected async Task TestAllInRegularAndScriptAsync( string input, TestParameters parameters, params string[] outputs) { for (var index = 0; index < outputs.Length; index++) { var output = outputs[index]; await TestInRegularAndScript1Async(input, output, index, parameters: parameters); } await TestActionCountAsync(input, outputs.Length, parameters); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Composition; using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; #if CODE_STYLE using System.Diagnostics; using System.IO; #else using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { [UseExportProvider] public abstract partial class AbstractCodeActionOrUserDiagnosticTest { public struct TestParameters { internal readonly OptionsCollection options; internal readonly TestHost testHost; internal readonly string workspaceKind; internal readonly object fixProviderData; internal readonly ParseOptions parseOptions; internal readonly CompilationOptions compilationOptions; internal readonly int index; internal readonly CodeActionPriority? priority; internal readonly bool retainNonFixableDiagnostics; internal readonly bool includeDiagnosticsOutsideSelection; internal readonly string title; internal TestParameters( ParseOptions parseOptions = null, CompilationOptions compilationOptions = null, OptionsCollection options = null, object fixProviderData = null, int index = 0, CodeActionPriority? priority = null, bool retainNonFixableDiagnostics = false, bool includeDiagnosticsOutsideSelection = false, string title = null, TestHost testHost = TestHost.InProcess, string workspaceKind = null) { this.parseOptions = parseOptions; this.compilationOptions = compilationOptions; this.options = options; this.fixProviderData = fixProviderData; this.index = index; this.priority = priority; this.retainNonFixableDiagnostics = retainNonFixableDiagnostics; this.includeDiagnosticsOutsideSelection = includeDiagnosticsOutsideSelection; this.title = title; this.testHost = testHost; this.workspaceKind = workspaceKind; } public TestParameters WithParseOptions(ParseOptions parseOptions) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithCompilationOptions(CompilationOptions compilationOptions) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); internal TestParameters WithOptions(OptionsCollection options) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithFixProviderData(object fixProviderData) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithIndex(int index) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithRetainNonFixableDiagnostics(bool retainNonFixableDiagnostics) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithIncludeDiagnosticsOutsideSelection(bool includeDiagnosticsOutsideSelection) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); public TestParameters WithWorkspaceKind(string workspaceKind) => new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, retainNonFixableDiagnostics, includeDiagnosticsOutsideSelection, title, testHost, workspaceKind); } #pragma warning disable IDE0052 // Remove unread private members (unused when CODE_STYLE is set) private readonly ITestOutputHelper _logger; #pragma warning restore protected AbstractCodeActionOrUserDiagnosticTest(ITestOutputHelper logger = null) { _logger = logger; } private const string AutoGeneratedAnalyzerConfigHeader = @"# auto-generated .editorconfig for code style options"; protected internal abstract string GetLanguage(); protected ParenthesesOptionsProvider ParenthesesOptionsProvider => new ParenthesesOptionsProvider(this.GetLanguage()); protected abstract ParseOptions GetScriptOptions(); private protected virtual IDocumentServiceProvider GetDocumentServiceProvider() => null; protected virtual TestComposition GetComposition() => EditorTestCompositions.EditorFeatures .AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService)) .AddParts(typeof(MockDiagnosticUpdateSourceRegistrationService)); protected virtual void InitializeWorkspace(TestWorkspace workspace, TestParameters parameters) { } protected virtual TestParameters SetParameterDefaults(TestParameters parameters) => parameters; protected TestWorkspace CreateWorkspaceFromOptions(string workspaceMarkupOrCode, TestParameters parameters) { var composition = GetComposition().WithTestHostParts(parameters.testHost); parameters = SetParameterDefaults(parameters); var documentServiceProvider = GetDocumentServiceProvider(); var workspace = TestWorkspace.IsWorkspaceElement(workspaceMarkupOrCode) ? TestWorkspace.Create(XElement.Parse(workspaceMarkupOrCode), openDocuments: false, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind) : TestWorkspace.Create(GetLanguage(), parameters.compilationOptions, parameters.parseOptions, files: new[] { workspaceMarkupOrCode }, composition: composition, documentServiceProvider: documentServiceProvider, workspaceKind: parameters.workspaceKind); #if !CODE_STYLE if (parameters.testHost == TestHost.OutOfProcess && _logger != null) { var remoteHostProvider = (InProcRemoteHostClientProvider)workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); remoteHostProvider.TraceListener = new XunitTraceListener(_logger); } #endif InitializeWorkspace(workspace, parameters); // For CodeStyle layer testing, we create an .editorconfig at project root // to apply the options as workspace options are not available in CodeStyle layer. // Otherwise, we apply the options directly to the workspace. #if CODE_STYLE // We need to ensure that our projects/documents are rooted for // execution from CodeStyle layer as we will be adding a rooted .editorconfig to each project // to apply the options. if (parameters.options != null) { MakeProjectsAndDocumentsRooted(workspace); AddAnalyzerConfigDocumentWithOptions(workspace, parameters.options); } #else workspace.ApplyOptions(parameters.options); #endif return workspace; } #if CODE_STYLE private static void MakeProjectsAndDocumentsRooted(TestWorkspace workspace) { const string defaultRootFilePath = @"z:\"; var newSolution = workspace.CurrentSolution; foreach (var projectId in workspace.CurrentSolution.ProjectIds) { var project = newSolution.GetProject(projectId); string projectRootFilePath; if (!PathUtilities.IsAbsolute(project.FilePath)) { projectRootFilePath = defaultRootFilePath; newSolution = newSolution.WithProjectFilePath(projectId, Path.Combine(projectRootFilePath, project.FilePath)); } else { projectRootFilePath = PathUtilities.GetPathRoot(project.FilePath); } foreach (var documentId in project.DocumentIds) { var document = newSolution.GetDocument(documentId); if (!PathUtilities.IsAbsolute(document.FilePath)) { newSolution = newSolution.WithDocumentFilePath(documentId, Path.Combine(projectRootFilePath, document.FilePath)); } else { Assert.Equal(projectRootFilePath, PathUtilities.GetPathRoot(document.FilePath)); } } } var applied = workspace.TryApplyChanges(newSolution); Assert.True(applied); return; } private static void AddAnalyzerConfigDocumentWithOptions(TestWorkspace workspace, OptionsCollection options) { Debug.Assert(options != null); var analyzerConfigText = GenerateAnalyzerConfigText(options); var newSolution = workspace.CurrentSolution; foreach (var project in workspace.Projects) { Assert.True(PathUtilities.IsAbsolute(project.FilePath)); var projectRootFilePath = PathUtilities.GetPathRoot(project.FilePath); var documentId = DocumentId.CreateNewId(project.Id); newSolution = newSolution.AddAnalyzerConfigDocument( documentId, ".editorconfig", SourceText.From(analyzerConfigText), filePath: Path.Combine(projectRootFilePath, ".editorconfig")); } var applied = workspace.TryApplyChanges(newSolution); Assert.True(applied); return; string GenerateAnalyzerConfigText(OptionsCollection options) { var textBuilder = new StringBuilder(); // Add an auto-generated header at the top so we can skip this file in expected baseline validation. textBuilder.AppendLine(AutoGeneratedAnalyzerConfigHeader); textBuilder.AppendLine(); textBuilder.AppendLine(options.GetEditorConfigText()); return textBuilder.ToString(); } } #endif private static TestParameters WithRegularOptions(TestParameters parameters) => parameters.WithParseOptions(parameters.parseOptions?.WithKind(SourceCodeKind.Regular)); private TestParameters WithScriptOptions(TestParameters parameters) => parameters.WithParseOptions(parameters.parseOptions?.WithKind(SourceCodeKind.Script) ?? GetScriptOptions()); protected async Task TestMissingInRegularAndScriptAsync( string initialMarkup, TestParameters parameters = default, int codeActionIndex = 0) { await TestMissingAsync(initialMarkup, WithRegularOptions(parameters), codeActionIndex); await TestMissingAsync(initialMarkup, WithScriptOptions(parameters), codeActionIndex); } protected async Task TestMissingAsync( string initialMarkup, TestParameters parameters = default, int codeActionIndex = 0) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var offeredActions = Environment.NewLine + string.Join(Environment.NewLine, actions.Select(action => action.Title)); if (codeActionIndex == 0) { Assert.True(actions.Length == 0, "An action was offered when none was expected. Offered actions:" + offeredActions); } else { Assert.True(actions.Length <= codeActionIndex, "An action was offered at the specified index when none was expected. Offered actions:" + offeredActions); } } } protected async Task TestDiagnosticMissingAsync( string initialMarkup, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var diagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters); Assert.True(0 == diagnostics.Length, $"Expected no diagnostics, but got {diagnostics.Length}"); } } protected abstract Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters); protected abstract Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync( TestWorkspace workspace, TestParameters parameters); protected Task TestSmartTagTextAsync(string initialMarkup, string displayText, int index) => TestSmartTagTextAsync(initialMarkup, displayText, new TestParameters(index: index)); protected Task TestSmartTagGlyphTagsAsync(string initialMarkup, ImmutableArray<string> glyphTags, int index) => TestSmartTagGlyphTagsAsync(initialMarkup, glyphTags, new TestParameters(index: index)); protected async Task TestSmartTagTextAsync( string initialMarkup, string displayText, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(displayText, action.Title); } } protected async Task TestSmartTagGlyphTagsAsync( string initialMarkup, ImmutableArray<string> glyph, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (_, action) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(glyph, action.Tags); } } protected async Task TestExactActionSetOfferedAsync( string initialMarkup, IEnumerable<string> expectedActionSet, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); var actualActionSet = actions.Select(a => a.Title); Assert.True(actualActionSet.SequenceEqual(expectedActionSet), "Expected: " + string.Join(", ", expectedActionSet) + "\nActual: " + string.Join(", ", actualActionSet)); } } protected async Task TestActionCountAsync( string initialMarkup, int count, TestParameters parameters = default) { using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var (actions, _) = await GetCodeActionsAsync(workspace, parameters); Assert.Equal(count, actions.Length); } } internal Task TestInRegularAndScriptAsync( string initialMarkup, string expectedMarkup, int index = 0, CodeActionPriority? priority = null, CompilationOptions compilationOptions = null, OptionsCollection options = null, object fixProviderData = null, ParseOptions parseOptions = null, string title = null, TestHost testHost = TestHost.InProcess) { return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, title: title, testHost: testHost)); } internal Task TestInRegularAndScript1Async( string initialMarkup, string expectedMarkup, int index = 0, TestParameters parameters = default) { return TestInRegularAndScript1Async(initialMarkup, expectedMarkup, parameters.WithIndex(index)); } internal async Task TestInRegularAndScript1Async( string initialMarkup, string expectedMarkup, TestParameters parameters) { await TestAsync(initialMarkup, expectedMarkup, WithRegularOptions(parameters)); // VB scripting is not supported: if (GetLanguage() == LanguageNames.CSharp) { await TestAsync(initialMarkup, expectedMarkup, WithScriptOptions(parameters)); } } internal Task TestAsync( string initialMarkup, string expectedMarkup, ParseOptions parseOptions, CompilationOptions compilationOptions = null, int index = 0, OptionsCollection options = null, object fixProviderData = null, CodeActionPriority? priority = null, TestHost testHost = TestHost.InProcess) { return TestAsync( initialMarkup, expectedMarkup, new TestParameters(parseOptions, compilationOptions, options, fixProviderData, index, priority, testHost: testHost)); } private async Task TestAsync( string initialMarkup, string expectedMarkup, TestParameters parameters) { MarkupTestFile.GetSpans( initialMarkup.NormalizeLineEndings(), out var initialMarkupWithoutSpans, out IDictionary<string, ImmutableArray<TextSpan>> initialSpanMap); const string UnnecessaryMarkupKey = "Unnecessary"; var unnecessarySpans = initialSpanMap.GetOrAdd(UnnecessaryMarkupKey, _ => ImmutableArray<TextSpan>.Empty); MarkupTestFile.GetSpans( expectedMarkup.NormalizeLineEndings(), out var expected, out IDictionary<string, ImmutableArray<TextSpan>> expectedSpanMap); var conflictSpans = expectedSpanMap.GetOrAdd("Conflict", _ => ImmutableArray<TextSpan>.Empty); var renameSpans = expectedSpanMap.GetOrAdd("Rename", _ => ImmutableArray<TextSpan>.Empty); var warningSpans = expectedSpanMap.GetOrAdd("Warning", _ => ImmutableArray<TextSpan>.Empty); var navigationSpans = expectedSpanMap.GetOrAdd("Navigation", _ => ImmutableArray<TextSpan>.Empty); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { // Ideally this check would always run, but there are several hundred tests that would need to be // updated with {|Unnecessary:|} spans. if (unnecessarySpans.Any()) { var allDiagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters .WithRetainNonFixableDiagnostics(true) .WithIncludeDiagnosticsOutsideSelection(true)); TestUnnecessarySpans(allDiagnostics, unnecessarySpans, UnnecessaryMarkupKey, initialMarkupWithoutSpans); } var (_, action) = await GetCodeActionsAsync(workspace, parameters); await TestActionAsync( workspace, expected, action, conflictSpans, renameSpans, warningSpans, navigationSpans, parameters); } } private static void TestUnnecessarySpans( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<TextSpan> expectedSpans, string markupKey, string initialMarkupWithoutSpans) { var unnecessaryLocations = diagnostics.SelectMany(GetUnnecessaryLocations) .OrderBy(location => location.SourceSpan.Start) .ThenBy(location => location.SourceSpan.End) .ToArray(); if (expectedSpans.Length != unnecessaryLocations.Length) { AssertEx.Fail(BuildFailureMessage(expectedSpans, WellKnownDiagnosticTags.Unnecessary, markupKey, initialMarkupWithoutSpans, diagnostics)); } for (var i = 0; i < expectedSpans.Length; i++) { var actual = unnecessaryLocations[i].SourceSpan; var expected = expectedSpans[i]; Assert.Equal(expected, actual); } static IEnumerable<Location> GetUnnecessaryLocations(Diagnostic diagnostic) { if (diagnostic.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary)) yield return diagnostic.Location; if (!diagnostic.Properties.TryGetValue(WellKnownDiagnosticTags.Unnecessary, out var additionalUnnecessaryLocationsString)) yield break; var locations = JArray.Parse(additionalUnnecessaryLocationsString); foreach (var locationIndex in locations) yield return diagnostic.AdditionalLocations[(int)locationIndex]; } } private static string BuildFailureMessage( ImmutableArray<TextSpan> expectedSpans, string diagnosticTag, string markupKey, string initialMarkupWithoutSpans, ImmutableArray<Diagnostic> diagnosticsWithTag) { var message = $"Expected {expectedSpans.Length} diagnostic spans with custom tag '{diagnosticTag}', but there were {diagnosticsWithTag.Length}."; if (expectedSpans.Length == 0) { message += $" If a diagnostic span tagged '{diagnosticTag}' is expected, surround the span in the test markup with the following syntax: {{|Unnecessary:...}}"; var segments = new List<(int originalStringIndex, string segment)>(); foreach (var diagnostic in diagnosticsWithTag) { var documentOffset = initialMarkupWithoutSpans.IndexOf(diagnosticsWithTag.First().Location.SourceTree.ToString()); if (documentOffset == -1) continue; segments.Add((documentOffset + diagnostic.Location.SourceSpan.Start, "{|" + markupKey + ":")); segments.Add((documentOffset + diagnostic.Location.SourceSpan.End, "|}")); } if (segments.Any()) { message += Environment.NewLine + "Example:" + Environment.NewLine + Environment.NewLine + InsertSegments(initialMarkupWithoutSpans, segments); } } return message; } private static string InsertSegments(string originalString, IEnumerable<(int originalStringIndex, string segment)> segments) { var builder = new StringBuilder(); var positionInOriginalString = 0; foreach (var (originalStringIndex, segment) in segments.OrderBy(s => s.originalStringIndex)) { builder.Append(originalString, positionInOriginalString, originalStringIndex - positionInOriginalString); builder.Append(segment); positionInOriginalString = originalStringIndex; } builder.Append(originalString, positionInOriginalString, originalString.Length - positionInOriginalString); return builder.ToString(); } internal async Task<Tuple<Solution, Solution>> TestActionAsync( TestWorkspace workspace, string expected, CodeAction action, ImmutableArray<TextSpan> conflictSpans, ImmutableArray<TextSpan> renameSpans, ImmutableArray<TextSpan> warningSpans, ImmutableArray<TextSpan> navigationSpans, TestParameters parameters) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, parameters); return await TestOperationsAsync( workspace, expected, operations, conflictSpans, renameSpans, warningSpans, navigationSpans, expectedChangedDocumentId: null); } protected static async Task<Tuple<Solution, Solution>> TestOperationsAsync( TestWorkspace workspace, string expectedText, ImmutableArray<CodeActionOperation> operations, ImmutableArray<TextSpan> conflictSpans, ImmutableArray<TextSpan> renameSpans, ImmutableArray<TextSpan> warningSpans, ImmutableArray<TextSpan> navigationSpans, DocumentId expectedChangedDocumentId) { var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; if (TestWorkspace.IsWorkspaceElement(expectedText)) { var newSolutionWithLinkedFiles = await newSolution.WithMergedLinkedFileChangesAsync(oldSolution); await VerifyAgainstWorkspaceDefinitionAsync(expectedText, newSolutionWithLinkedFiles, workspace.ExportProvider); return Tuple.Create(oldSolution, newSolution); } var document = GetDocumentToVerify(expectedChangedDocumentId, oldSolution, newSolution); var fixedRoot = await document.GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); // To help when a user just writes a test (and supplied no 'expectedText') just print // out the entire 'actualText' (without any trimming). in the case that we have both, // call the normal AssertEx helper which will print out a good diff. if (expectedText == "") { Assert.Equal((object)expectedText, actualText); } else { AssertEx.EqualOrDiff(expectedText, actualText); } TestAnnotations(conflictSpans, ConflictAnnotation.Kind); TestAnnotations(renameSpans, RenameAnnotation.Kind); TestAnnotations(warningSpans, WarningAnnotation.Kind); TestAnnotations(navigationSpans, NavigationAnnotation.Kind); return Tuple.Create(oldSolution, newSolution); void TestAnnotations(ImmutableArray<TextSpan> expectedSpans, string annotationKind) { var annotatedItems = fixedRoot.GetAnnotatedNodesAndTokens(annotationKind).OrderBy(s => s.SpanStart).ToList(); Assert.True(expectedSpans.Length == annotatedItems.Count, $"Annotations of kind '{annotationKind}' didn't match. Expected: {expectedSpans.Length}. Actual: {annotatedItems.Count}."); for (var i = 0; i < Math.Min(expectedSpans.Length, annotatedItems.Count); i++) { var actual = annotatedItems[i].Span; var expected = expectedSpans[i]; Assert.Equal(expected, actual); } } } protected static Document GetDocumentToVerify(DocumentId expectedChangedDocumentId, Solution oldSolution, Solution newSolution) { Document document; // If the expectedChangedDocumentId is not mentioned then we expect only single document to be changed if (expectedChangedDocumentId == null) { var projectDifferences = SolutionUtilities.GetSingleChangedProjectChanges(oldSolution, newSolution); var documentId = projectDifferences.GetChangedDocuments().FirstOrDefault() ?? projectDifferences.GetAddedDocuments().FirstOrDefault(); Assert.NotNull(documentId); document = newSolution.GetDocument(documentId); } else { // This method obtains only the document changed and does not check the project state. document = newSolution.GetDocument(expectedChangedDocumentId); } return document; } private static async Task VerifyAgainstWorkspaceDefinitionAsync(string expectedText, Solution newSolution, ExportProvider exportProvider) { using (var expectedWorkspace = TestWorkspace.Create(expectedText, exportProvider: exportProvider)) { var expectedSolution = expectedWorkspace.CurrentSolution; Assert.Equal(expectedSolution.Projects.Count(), newSolution.Projects.Count()); foreach (var project in newSolution.Projects) { var expectedProject = expectedSolution.GetProjectsByName(project.Name).Single(); Assert.Equal(expectedProject.Documents.Count(), project.Documents.Count()); foreach (var doc in project.Documents) { var root = await doc.GetSyntaxRootAsync(); var expectedDocuments = expectedProject.Documents.Where(d => d.Name == doc.Name); if (expectedDocuments.Any()) { Assert.Single(expectedDocuments); } else { AssertEx.Fail($"Could not find document with name '{doc.Name}'"); } var expectedDocument = expectedDocuments.Single(); var expectedRoot = await expectedDocument.GetSyntaxRootAsync(); VerifyExpectedDocumentText(expectedRoot.ToFullString(), root.ToFullString()); } foreach (var additionalDoc in project.AdditionalDocuments) { var root = await additionalDoc.GetTextAsync(); var expectedDocument = expectedProject.AdditionalDocuments.Single(d => d.Name == additionalDoc.Name); var expectedRoot = await expectedDocument.GetTextAsync(); VerifyExpectedDocumentText(expectedRoot.ToString(), root.ToString()); } foreach (var analyzerConfigDoc in project.AnalyzerConfigDocuments) { var root = await analyzerConfigDoc.GetTextAsync(); var actualString = root.ToString(); if (actualString.StartsWith(AutoGeneratedAnalyzerConfigHeader)) { // Skip validation for analyzer config file that is auto-generated by test framework // for applying code style options. continue; } var expectedDocument = expectedProject.AnalyzerConfigDocuments.Single(d => d.FilePath == analyzerConfigDoc.FilePath); var expectedRoot = await expectedDocument.GetTextAsync(); VerifyExpectedDocumentText(expectedRoot.ToString(), actualString); } } } return; // Local functions. static void VerifyExpectedDocumentText(string expected, string actual) { if (expected == "") { Assert.Equal((object)expected, actual); } else { Assert.Equal(expected, actual); } } } internal async Task<ImmutableArray<CodeActionOperation>> VerifyActionAndGetOperationsAsync( TestWorkspace workspace, CodeAction action, TestParameters parameters) { if (action is null) { var diagnostics = await GetDiagnosticsWorkerAsync(workspace, parameters.WithRetainNonFixableDiagnostics(true)); throw new Exception("No action was offered when one was expected. Diagnostics from the compilation: " + string.Join("", diagnostics.Select(d => Environment.NewLine + d.ToString()))); } if (parameters.priority != null) { Assert.Equal(parameters.priority.Value, action.Priority); } if (parameters.title != null) { Assert.Equal(parameters.title, action.Title); } return await action.GetOperationsAsync(CancellationToken.None); } protected static Tuple<Solution, Solution> ApplyOperationsAndGetSolution( TestWorkspace workspace, IEnumerable<CodeActionOperation> operations) { Tuple<Solution, Solution> result = null; foreach (var operation in operations) { if (operation is ApplyChangesOperation && result == null) { var oldSolution = workspace.CurrentSolution; var newSolution = ((ApplyChangesOperation)operation).ChangedSolution; result = Tuple.Create(oldSolution, newSolution); } else if (operation.ApplyDuringTests) { var oldSolution = workspace.CurrentSolution; operation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); var newSolution = workspace.CurrentSolution; result = Tuple.Create(oldSolution, newSolution); } } if (result == null) { throw new InvalidOperationException("No ApplyChangesOperation found"); } return result; } protected virtual ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => actions; internal static void VerifyCodeActionsRegisteredByProvider(CodeFixProvider provider, List<CodeFix> fixes) { if (provider.GetFixAllProvider() == null) { // Only require unique equivalence keys when the fixer supports FixAll return; } var diagnosticsAndEquivalenceKeyToTitleMap = new Dictionary<(Diagnostic diagnostic, string equivalenceKey), string>(); foreach (var fix in fixes) { VerifyCodeAction(fix.Action, fix.Diagnostics, provider, diagnosticsAndEquivalenceKeyToTitleMap); } return; static void VerifyCodeAction( CodeAction codeAction, ImmutableArray<Diagnostic> diagnostics, CodeFixProvider provider, Dictionary<(Diagnostic diagnostic, string equivalenceKey), string> diagnosticsAndEquivalenceKeyToTitleMap) { if (!codeAction.NestedCodeActions.IsEmpty) { // Only validate leaf code actions. foreach (var nestedAction in codeAction.NestedCodeActions) { VerifyCodeAction(nestedAction, diagnostics, provider, diagnosticsAndEquivalenceKeyToTitleMap); } return; } foreach (var diagnostic in diagnostics) { var key = (diagnostic, codeAction.EquivalenceKey); var existingTitle = diagnosticsAndEquivalenceKeyToTitleMap.GetOrAdd(key, _ => codeAction.Title); if (existingTitle != codeAction.Title) { var messageSuffix = codeAction.EquivalenceKey != null ? string.Empty : @" Consider using the title as the equivalence key instead of 'null'"; Assert.False(true, @$"Expected different 'CodeAction.EquivalenceKey' for code actions registered for same diagnostic: - Name: '{provider.GetType().Name}' - Title 1: '{codeAction.Title}' - Title 2: '{existingTitle}' - Shared equivalence key: '{codeAction.EquivalenceKey ?? "<null>"}'{messageSuffix}"); } } } } protected static ImmutableArray<CodeAction> FlattenActions(ImmutableArray<CodeAction> codeActions) { return codeActions.SelectMany(a => a.NestedCodeActions.Length > 0 ? a.NestedCodeActions : ImmutableArray.Create(a)).ToImmutableArray(); } protected static ImmutableArray<CodeAction> GetNestedActions(ImmutableArray<CodeAction> codeActions) => codeActions.SelectMany(a => a.NestedCodeActions).ToImmutableArray(); /// <summary> /// Tests all the code actions for the given <paramref name="input"/> string. Each code /// action must produce the corresponding output in the <paramref name="outputs"/> array. /// /// Will throw if there are more outputs than code actions or more code actions than outputs. /// </summary> protected Task TestAllInRegularAndScriptAsync( string input, params string[] outputs) { return TestAllInRegularAndScriptAsync(input, parameters: default, outputs); } protected async Task TestAllInRegularAndScriptAsync( string input, TestParameters parameters, params string[] outputs) { for (var index = 0; index < outputs.Length; index++) { var output = outputs[index]; await TestInRegularAndScript1Async(input, output, index, parameters: parameters); } await TestActionCountAsync(input, outputs.Length, parameters); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/CompletionProviders/ImportCompletion/TypeImportCompletionServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared] internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace); private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService { public CSharpTypeImportCompletionService(Workspace workspace) : base(workspace) { } protected override string GenericTypeSuffix => "<>"; protected override bool IsCaseSensitive => true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportLanguageServiceFactory(typeof(ITypeImportCompletionService), LanguageNames.CSharp), Shared] internal sealed class TypeImportCompletionServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TypeImportCompletionServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => new CSharpTypeImportCompletionService(languageServices.WorkspaceServices.Workspace); private class CSharpTypeImportCompletionService : AbstractTypeImportCompletionService { public CSharpTypeImportCompletionService(Workspace workspace) : base(workspace) { } protected override string GenericTypeSuffix => "<>"; protected override bool IsCaseSensitive => true; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/NavigateTo/INavigateToSearchResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/UseInferredMemberName/CSharpUseInferredMemberNameDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UseInferredMemberName; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseInferredMemberName { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUseInferredMemberNameDiagnosticAnalyzer : AbstractUseInferredMemberNameDiagnosticAnalyzer { protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.NameColon, SyntaxKind.NameEquals); protected override void LanguageSpecificAnalyzeSyntax(SyntaxNodeAnalysisContext context, SyntaxTree syntaxTree, AnalyzerOptions options, CancellationToken cancellationToken) { switch (context.Node.Kind()) { case SyntaxKind.NameColon: ReportDiagnosticsIfNeeded((NameColonSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; case SyntaxKind.NameEquals: ReportDiagnosticsIfNeeded((NameEqualsSyntax)context.Node, context, options, syntaxTree, cancellationToken); break; } } private void ReportDiagnosticsIfNeeded(NameColonSyntax nameColon, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameColon.Parent.IsKind(SyntaxKind.Argument, out ArgumentSyntax? argument)) { return; } var parseOptions = (CSharpParseOptions)syntaxTree.Options; var preference = options.GetOption( CodeStyleOptions2.PreferInferredTupleNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyTupleElementName(argument, parseOptions)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameColon.Name.SpanStart, nameColon.ColonToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameColon.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } private void ReportDiagnosticsIfNeeded(NameEqualsSyntax nameEquals, SyntaxNodeAnalysisContext context, AnalyzerOptions options, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (!nameEquals.Parent.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonCtor)) { return; } var preference = options.GetOption( CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, context.Compilation.Language, syntaxTree, cancellationToken); if (!preference.Value || !CSharpInferredMemberNameSimplifier.CanSimplifyAnonymousTypeMemberName(anonCtor)) { return; } // Create a normal diagnostic var fadeSpan = TextSpan.FromBounds(nameEquals.Name.SpanStart, nameEquals.EqualsToken.Span.End); context.ReportDiagnostic( DiagnosticHelper.CreateWithLocationTags( Descriptor, nameEquals.GetLocation(), preference.Notification.Severity, additionalLocations: ImmutableArray<Location>.Empty, additionalUnnecessaryLocations: ImmutableArray.Create(syntaxTree.GetLocation(fadeSpan)))); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackDispatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteServiceCallbackDispatcher { RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance); } internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { internal readonly struct Handle : IDisposable { private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances; public readonly RemoteServiceCallbackId Id; public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId) { _callbackInstances = callbackInstances; Id = callbackId; } public void Dispose() { Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false); } } private int _callbackId = 1; private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10); public Handle CreateHandle(object? instance) { if (instance is null) { return default; } var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId)); var handle = new Handle(_callbackInstances, callbackId); _callbackInstances.Add(callbackId, instance); return handle; } public object GetCallback(RemoteServiceCallbackId callbackId) { Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance)); return instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteServiceCallbackDispatcher { RemoteServiceCallbackDispatcher.Handle CreateHandle(object? instance); } internal class RemoteServiceCallbackDispatcher : IRemoteServiceCallbackDispatcher { internal readonly struct Handle : IDisposable { private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances; public readonly RemoteServiceCallbackId Id; public Handle(ConcurrentDictionary<RemoteServiceCallbackId, object> callbackInstances, RemoteServiceCallbackId callbackId) { _callbackInstances = callbackInstances; Id = callbackId; } public void Dispose() { Contract.ThrowIfTrue(_callbackInstances?.TryRemove(Id, out _) == false); } } private int _callbackId = 1; private readonly ConcurrentDictionary<RemoteServiceCallbackId, object> _callbackInstances = new(concurrencyLevel: 2, capacity: 10); public Handle CreateHandle(object? instance) { if (instance is null) { return default; } var callbackId = new RemoteServiceCallbackId(Interlocked.Increment(ref _callbackId)); var handle = new Handle(_callbackInstances, callbackId); _callbackInstances.Add(callbackId, instance); return handle; } public object GetCallback(RemoteServiceCallbackId callbackId) { Contract.ThrowIfFalse(_callbackInstances.TryGetValue(callbackId, out var instance)); return instance; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/CodeGen/DestructorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class DestructorTests : EmitMetadataTestBase { [ConditionalFact(typeof(DesktopOnly))] public void ClassDestructor() { var text = @" using System; public class Base { ~Base() { Console.WriteLine(""~Base""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Base"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedClassDestructor() { var text = @" using System; public class Base { ~Base() => Console.WriteLine(""~Base""); } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Base"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedSubClassDestructor() { var text = @" using System; public class Base { ~Base() => Console.WriteLine(""~Base""); } public class Derived : Base { ~Derived() => Console.WriteLine(""~Derived""); } public class Program { public static void Main() { Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyIL("Derived.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Derived"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void Base.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] public void SubclassDestructor() { var text = @" using System; public class Base { ~Base() { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Derived(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyIL("Derived.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Derived"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void Base.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly))] public void DestructorOverridesNonDestructor() { var text = @" using System; public class Base { protected virtual void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() //NB: in metadata, this will implicitly override Base.Finalize, but explicitly override Object.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var expectedOutput = @" ~Derived ~Base "; // Destructors generated by Roslyn should still be destructors when they are loaded back in - // even in cases where the user creates their own Finalize methods (which is legal, but ill-advised). // This may not be the case for metadata from other C# compilers (which will likely not have // destructors explicitly override System.Object.Finalize). var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput, expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig newslot virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,28): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [WorkItem(542828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542828")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void BaseTypeHasNonVirtualFinalize() { var text = @" using System; public class Base { protected void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() //NB: in metadata, this will override Base.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,20): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [WorkItem(542828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542828")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void GenericBaseTypeHasNonVirtualFinalize() { var text = @" using System; public class Base<T> { protected void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base<int> { ~Derived() //NB: in metadata, this will override Base.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base<char> b = new Base<char>(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base`1", "Finalize", ".method family hidebysig instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,20): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void StructAndInterfaceHasNonVirtualFinalize() { var text = @" public interface I { void Finalize(); } public struct S { void Finalize() { } } class C { private string Finalize; } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyDiagnostics( // (4,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize(); Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize() { } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (14,20): warning CS0169: The field 'C.Finalize' is never used // private string Finalize; Diagnostic(ErrorCode.WRN_UnreferencedField, "Finalize").WithArguments("C.Finalize") ); } [Fact] public void IsRuntimeFinalizer1() { var text = @" public class A { ~A() { } } public class B { public virtual void Finalize() { } } public class C : A { public void Finalize() { } } public class D : B { public override void Finalize() { } } public struct E { public void Finalize() { } } public interface F { void Finalize(); } public class G { protected virtual void Finalize() { } } public class H : G { ~H() { } } public class I { protected virtual void Finalize<T>() { } } public class J<T> { protected virtual void Finalize() { } } public class K<T> { ~K() { } } public class L<T> { ~L() { } } public class M<T> : L<T> { ~M() { } } "; Action<ModuleSymbol> validator = module => { var globalNamespace = module.GlobalNamespace; var mscorlib = module.ContainingAssembly.CorLibrary; var systemNamespace = mscorlib.GlobalNamespace.GetMember<NamespaceSymbol>("System"); Assert.True(systemNamespace.GetMember<NamedTypeSymbol>("Object").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("F").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("G").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("H").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var intType = systemNamespace.GetMember<TypeSymbol>("Int32"); Assert.Equal(SpecialType.System_Int32, intType.SpecialType); var classJ = globalNamespace.GetMember<NamedTypeSymbol>("J"); Assert.False(classJ.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classJInt = classJ.Construct(intType); Assert.False(classJInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classK = globalNamespace.GetMember<NamedTypeSymbol>("K"); Assert.True(classK.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classKInt = classK.Construct(intType); Assert.True(classKInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classL = globalNamespace.GetMember<NamedTypeSymbol>("L"); Assert.True(classL.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classLInt = classL.Construct(intType); Assert.True(classLInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classM = globalNamespace.GetMember<NamedTypeSymbol>("M"); Assert.True(classM.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classMInt = classM.Construct(intType); Assert.True(classMInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); }; CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void IsRuntimeFinalizer2() { var text = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method family hidebysig virtual instance void Finalize() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C .class public auto ansi beforefieldinit D extends [mscorlib]System.Object { .method family hidebysig newslot virtual instance void Finalize() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class D "; var compilation = CreateCompilationWithILAndMscorlib40("", text); var globalNamespace = compilation.GlobalNamespace; Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); //override of object.Finalize Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); //same but has "newslot" } [WorkItem(528903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528903")] // Won't fix - test just captures behavior. [Fact] public void DestructorOverridesPublicFinalize() { var text = @" public class A { public virtual void Finalize() { } } public class B : A { ~B() { } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll); // NOTE: has warnings, but not errors. compilation.VerifyDiagnostics( // (4,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // public virtual void Finalize() { } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); // We produce unverifiable code here as per bug resolution (compat concerns, not common case). CompileAndVerify(compilation, verify: Verification.Fails).VerifyIL("B.Finalize", @" { // Code size 10 (0xa) .maxstack 1 .try { IL_0000: leave.s IL_0009 } finally { IL_0002: ldarg.0 IL_0003: call ""void object.Finalize()"" IL_0008: endfinally } IL_0009: ret } "); } [WorkItem(528907, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528907")] [Fact] public void BaseTypeHasGenericFinalize() { var text = @" public class A { protected void Finalize<T>() { } } public class B : A { ~B() { } } "; // NOTE: calling object.Finalize, since A.Finalize has the wrong arity. // (Dev11 called A.Finalize and failed at runtime, since it wasn't providing // a type argument.) CompileAndVerify(text).VerifyIL("B.Finalize", @" { // Code size 10 (0xa) .maxstack 1 .try { IL_0000: leave.s IL_0009 } finally { IL_0002: ldarg.0 IL_0003: call ""void object.Finalize()"" IL_0008: endfinally } IL_0009: ret } "); } [WorkItem(528903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528903")] [Fact] public void MethodImplEntry() { var text = @" public class A { ~A() { } } "; CompileAndVerify(text, assemblyValidator: (assembly) => { var peFileReader = assembly.GetMetadataReader(); // Find the handle and row for A. var pairA = peFileReader.TypeDefinitions.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetTypeDefinition(handle) }). Single(pair => peFileReader.GetString(pair.row.Name) == "A" && string.IsNullOrEmpty(peFileReader.GetString(pair.row.Namespace))); TypeDefinitionHandle handleA = pairA.handle; TypeDefinition typeA = pairA.row; // Find the handle for A's destructor. MethodDefinitionHandle handleDestructorA = typeA.GetMethods().AsEnumerable(). Single(handle => peFileReader.GetString(peFileReader.GetMethodDefinition(handle).Name) == WellKnownMemberNames.DestructorName); // Find the handle for System.Object. TypeReferenceHandle handleObject = peFileReader.TypeReferences.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetTypeReference(handle) }). Single(pair => peFileReader.GetString(pair.row.Name) == "Object" && peFileReader.GetString(pair.row.Namespace) == "System").handle; // Find the handle for System.Object's destructor. MemberReferenceHandle handleDestructorObject = peFileReader.MemberReferences.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetMemberReference(handle) }). Single(pair => pair.row.Parent == (EntityHandle)handleObject && peFileReader.GetString(pair.row.Name) == WellKnownMemberNames.DestructorName).handle; // Find the MethodImpl row for A. MethodImplementation methodImpl = typeA.GetMethodImplementations().AsEnumerable(). Select(handle => peFileReader.GetMethodImplementation(handle)). Single(); // The Class column should point to A. Assert.Equal(handleA, methodImpl.Type); // The MethodDeclaration column should point to System.Object.Finalize. Assert.Equal((EntityHandle)handleDestructorObject, methodImpl.MethodDeclaration); // The MethodDeclarationColumn should point to A's destructor. Assert.Equal((EntityHandle)handleDestructorA, methodImpl.MethodBody); }); } private static Action<ModuleSymbol> GetDestructorValidator(string typeName) { return module => ValidateDestructor(module, typeName); } // NOTE: assumes there's a destructor. private static void ValidateDestructor(ModuleSymbol module, string typeName) { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName); var destructor = @class.GetMember<MethodSymbol>(WellKnownMemberNames.DestructorName); Assert.Equal(MethodKind.Destructor, destructor.MethodKind); Assert.True(destructor.IsMetadataVirtual()); Assert.False(destructor.IsVirtual); Assert.False(destructor.IsOverride); Assert.False(destructor.IsSealed); Assert.False(destructor.IsStatic); Assert.False(destructor.IsAbstract); Assert.Null(destructor.OverriddenMethod); Assert.Equal(SpecialType.System_Void, destructor.ReturnType.SpecialType); Assert.Equal(0, destructor.Parameters.Length); Assert.Equal(0, destructor.TypeParameters.Length); Assert.Equal(Accessibility.Protected, destructor.DeclaredAccessibility); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Collections.Generic; using System.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class DestructorTests : EmitMetadataTestBase { [ConditionalFact(typeof(DesktopOnly))] public void ClassDestructor() { var text = @" using System; public class Base { ~Base() { Console.WriteLine(""~Base""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Base"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedClassDestructor() { var text = @" using System; public class Base { ~Base() => Console.WriteLine(""~Base""); } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Base"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedSubClassDestructor() { var text = @" using System; public class Base { ~Base() => Console.WriteLine(""~Base""); } public class Derived : Base { ~Derived() => Console.WriteLine(""~Derived""); } public class Program { public static void Main() { Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyIL("Derived.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Derived"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void Base.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyDiagnostics(); } [ConditionalFact(typeof(DesktopOnly))] public void SubclassDestructor() { var text = @" using System; public class Base { ~Base() { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Derived(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyIL("Base.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Base"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void object.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyIL("Derived.Finalize", @" { // Code size 20 (0x14) .maxstack 1 .try { IL_0000: ldstr ""~Derived"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: leave.s IL_0013 } finally { IL_000c: ldarg.0 IL_000d: call ""void Base.Finalize()"" IL_0012: endfinally } IL_0013: ret } "); compVerifier.VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsDesktopOnly))] public void DestructorOverridesNonDestructor() { var text = @" using System; public class Base { protected virtual void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() //NB: in metadata, this will implicitly override Base.Finalize, but explicitly override Object.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var expectedOutput = @" ~Derived ~Base "; // Destructors generated by Roslyn should still be destructors when they are loaded back in - // even in cases where the user creates their own Finalize methods (which is legal, but ill-advised). // This may not be the case for metadata from other C# compilers (which will likely not have // destructors explicitly override System.Object.Finalize). var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput, expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig newslot virtual instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,28): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [WorkItem(542828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542828")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void BaseTypeHasNonVirtualFinalize() { var text = @" using System; public class Base { protected void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base { ~Derived() //NB: in metadata, this will override Base.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base b = new Base(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base", "Finalize", ".method family hidebysig instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,20): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [WorkItem(542828, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542828")] [ConditionalFact(typeof(WindowsDesktopOnly))] public void GenericBaseTypeHasNonVirtualFinalize() { var text = @" using System; public class Base<T> { protected void Finalize() //NB: does not override Object.Finalize { Console.WriteLine(""~Base""); } } public class Derived : Base<int> { ~Derived() //NB: in metadata, this will override Base.Finalize { Console.WriteLine(""~Derived""); } } public class Program { public static void Main() { Base<char> b = new Base<char>(); b = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); Derived d = new Derived(); d = null; GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); } } "; var validator = GetDestructorValidator("Derived"); var compVerifier = CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @"~Derived ~Base", expectedSignatures: new[] { Signature("Base`1", "Finalize", ".method family hidebysig instance System.Void Finalize() cil managed"), Signature("Derived", "Finalize", ".method family hidebysig virtual instance System.Void Finalize() cil managed") }); compVerifier.VerifyDiagnostics( // (6,20): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void StructAndInterfaceHasNonVirtualFinalize() { var text = @" public interface I { void Finalize(); } public struct S { void Finalize() { } } class C { private string Finalize; } "; var compVerifier = CompileAndVerify(text); compVerifier.VerifyDiagnostics( // (4,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize(); Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,10): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // void Finalize() { } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (14,20): warning CS0169: The field 'C.Finalize' is never used // private string Finalize; Diagnostic(ErrorCode.WRN_UnreferencedField, "Finalize").WithArguments("C.Finalize") ); } [Fact] public void IsRuntimeFinalizer1() { var text = @" public class A { ~A() { } } public class B { public virtual void Finalize() { } } public class C : A { public void Finalize() { } } public class D : B { public override void Finalize() { } } public struct E { public void Finalize() { } } public interface F { void Finalize(); } public class G { protected virtual void Finalize() { } } public class H : G { ~H() { } } public class I { protected virtual void Finalize<T>() { } } public class J<T> { protected virtual void Finalize() { } } public class K<T> { ~K() { } } public class L<T> { ~L() { } } public class M<T> : L<T> { ~M() { } } "; Action<ModuleSymbol> validator = module => { var globalNamespace = module.GlobalNamespace; var mscorlib = module.ContainingAssembly.CorLibrary; var systemNamespace = mscorlib.GlobalNamespace.GetMember<NamespaceSymbol>("System"); Assert.True(systemNamespace.GetMember<NamedTypeSymbol>("Object").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("E").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("F").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("G").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("H").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("I").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var intType = systemNamespace.GetMember<TypeSymbol>("Int32"); Assert.Equal(SpecialType.System_Int32, intType.SpecialType); var classJ = globalNamespace.GetMember<NamedTypeSymbol>("J"); Assert.False(classJ.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classJInt = classJ.Construct(intType); Assert.False(classJInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classK = globalNamespace.GetMember<NamedTypeSymbol>("K"); Assert.True(classK.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classKInt = classK.Construct(intType); Assert.True(classKInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classL = globalNamespace.GetMember<NamedTypeSymbol>("L"); Assert.True(classL.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classLInt = classL.Construct(intType); Assert.True(classLInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classM = globalNamespace.GetMember<NamedTypeSymbol>("M"); Assert.True(classM.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); var classMInt = classM.Construct(intType); Assert.True(classMInt.GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); }; CompileAndVerify(text, sourceSymbolValidator: validator, symbolValidator: validator); } [Fact] public void IsRuntimeFinalizer2() { var text = @" .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method family hidebysig virtual instance void Finalize() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class C .class public auto ansi beforefieldinit D extends [mscorlib]System.Object { .method family hidebysig newslot virtual instance void Finalize() cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class D "; var compilation = CreateCompilationWithILAndMscorlib40("", text); var globalNamespace = compilation.GlobalNamespace; Assert.True(globalNamespace.GetMember<NamedTypeSymbol>("C").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); //override of object.Finalize Assert.False(globalNamespace.GetMember<NamedTypeSymbol>("D").GetMember<MethodSymbol>("Finalize").IsRuntimeFinalizer()); //same but has "newslot" } [WorkItem(528903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528903")] // Won't fix - test just captures behavior. [Fact] public void DestructorOverridesPublicFinalize() { var text = @" public class A { public virtual void Finalize() { } } public class B : A { ~B() { } } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDll); // NOTE: has warnings, but not errors. compilation.VerifyDiagnostics( // (4,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? // public virtual void Finalize() { } Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); // We produce unverifiable code here as per bug resolution (compat concerns, not common case). CompileAndVerify(compilation, verify: Verification.Fails).VerifyIL("B.Finalize", @" { // Code size 10 (0xa) .maxstack 1 .try { IL_0000: leave.s IL_0009 } finally { IL_0002: ldarg.0 IL_0003: call ""void object.Finalize()"" IL_0008: endfinally } IL_0009: ret } "); } [WorkItem(528907, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528907")] [Fact] public void BaseTypeHasGenericFinalize() { var text = @" public class A { protected void Finalize<T>() { } } public class B : A { ~B() { } } "; // NOTE: calling object.Finalize, since A.Finalize has the wrong arity. // (Dev11 called A.Finalize and failed at runtime, since it wasn't providing // a type argument.) CompileAndVerify(text).VerifyIL("B.Finalize", @" { // Code size 10 (0xa) .maxstack 1 .try { IL_0000: leave.s IL_0009 } finally { IL_0002: ldarg.0 IL_0003: call ""void object.Finalize()"" IL_0008: endfinally } IL_0009: ret } "); } [WorkItem(528903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528903")] [Fact] public void MethodImplEntry() { var text = @" public class A { ~A() { } } "; CompileAndVerify(text, assemblyValidator: (assembly) => { var peFileReader = assembly.GetMetadataReader(); // Find the handle and row for A. var pairA = peFileReader.TypeDefinitions.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetTypeDefinition(handle) }). Single(pair => peFileReader.GetString(pair.row.Name) == "A" && string.IsNullOrEmpty(peFileReader.GetString(pair.row.Namespace))); TypeDefinitionHandle handleA = pairA.handle; TypeDefinition typeA = pairA.row; // Find the handle for A's destructor. MethodDefinitionHandle handleDestructorA = typeA.GetMethods().AsEnumerable(). Single(handle => peFileReader.GetString(peFileReader.GetMethodDefinition(handle).Name) == WellKnownMemberNames.DestructorName); // Find the handle for System.Object. TypeReferenceHandle handleObject = peFileReader.TypeReferences.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetTypeReference(handle) }). Single(pair => peFileReader.GetString(pair.row.Name) == "Object" && peFileReader.GetString(pair.row.Namespace) == "System").handle; // Find the handle for System.Object's destructor. MemberReferenceHandle handleDestructorObject = peFileReader.MemberReferences.AsEnumerable(). Select(handle => new { handle = handle, row = peFileReader.GetMemberReference(handle) }). Single(pair => pair.row.Parent == (EntityHandle)handleObject && peFileReader.GetString(pair.row.Name) == WellKnownMemberNames.DestructorName).handle; // Find the MethodImpl row for A. MethodImplementation methodImpl = typeA.GetMethodImplementations().AsEnumerable(). Select(handle => peFileReader.GetMethodImplementation(handle)). Single(); // The Class column should point to A. Assert.Equal(handleA, methodImpl.Type); // The MethodDeclaration column should point to System.Object.Finalize. Assert.Equal((EntityHandle)handleDestructorObject, methodImpl.MethodDeclaration); // The MethodDeclarationColumn should point to A's destructor. Assert.Equal((EntityHandle)handleDestructorA, methodImpl.MethodBody); }); } private static Action<ModuleSymbol> GetDestructorValidator(string typeName) { return module => ValidateDestructor(module, typeName); } // NOTE: assumes there's a destructor. private static void ValidateDestructor(ModuleSymbol module, string typeName) { var @class = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName); var destructor = @class.GetMember<MethodSymbol>(WellKnownMemberNames.DestructorName); Assert.Equal(MethodKind.Destructor, destructor.MethodKind); Assert.True(destructor.IsMetadataVirtual()); Assert.False(destructor.IsVirtual); Assert.False(destructor.IsOverride); Assert.False(destructor.IsSealed); Assert.False(destructor.IsStatic); Assert.False(destructor.IsAbstract); Assert.Null(destructor.OverriddenMethod); Assert.Equal(SpecialType.System_Void, destructor.ReturnType.SpecialType); Assert.Equal(0, destructor.Parameters.Length); Assert.Equal(0, destructor.TypeParameters.Length); Assert.Equal(Accessibility.Protected, destructor.DeclaredAccessibility); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Assert/WorkItemAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { /// <summary> /// Used to tag test methods or types which are created for a given WorkItem /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class WorkItemAttribute : Attribute { public int Id { get; } public string Location { get; } /// <summary> /// Initializes a new instance of the <see cref="WorkItemAttribute"/>. /// </summary> /// <param name="id">The ID of the issue in the original tracker where the work item was first reported. This /// could be a GitHub issue or pull request number, or the number of a Microsoft-internal bug.</param> /// <param name="issueUri">The URI where the work item can be viewed. This is a link to work item /// <paramref name="id"/> in the original source.</param> public WorkItemAttribute(int id, string issueUri) { Id = id; Location = issueUri; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Roslyn.Test.Utilities { /// <summary> /// Used to tag test methods or types which are created for a given WorkItem /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public sealed class WorkItemAttribute : Attribute { public int Id { get; } public string Location { get; } /// <summary> /// Initializes a new instance of the <see cref="WorkItemAttribute"/>. /// </summary> /// <param name="id">The ID of the issue in the original tracker where the work item was first reported. This /// could be a GitHub issue or pull request number, or the number of a Microsoft-internal bug.</param> /// <param name="issueUri">The URI where the work item can be viewed. This is a link to work item /// <paramref name="id"/> in the original source.</param> public WorkItemAttribute(int id, string issueUri) { Id = id; Location = issueUri; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarSelectedItems.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor { internal class NavigationBarSelectedTypeAndMember { public NavigationBarItem TypeItem { get; } public bool ShowTypeItemGrayed { get; } public NavigationBarItem MemberItem { get; } public bool ShowMemberItemGrayed { get; } public NavigationBarSelectedTypeAndMember(NavigationBarItem typeItem, NavigationBarItem memberItem) { TypeItem = typeItem; MemberItem = memberItem; } public NavigationBarSelectedTypeAndMember( NavigationBarItem typeItem, bool showTypeItemGrayed, NavigationBarItem memberItem, bool showMemberItemGrayed) : this(typeItem, memberItem) { ShowTypeItemGrayed = showTypeItemGrayed; ShowMemberItemGrayed = showMemberItemGrayed; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Editor { internal class NavigationBarSelectedTypeAndMember { public NavigationBarItem TypeItem { get; } public bool ShowTypeItemGrayed { get; } public NavigationBarItem MemberItem { get; } public bool ShowMemberItemGrayed { get; } public NavigationBarSelectedTypeAndMember(NavigationBarItem typeItem, NavigationBarItem memberItem) { TypeItem = typeItem; MemberItem = memberItem; } public NavigationBarSelectedTypeAndMember( NavigationBarItem typeItem, bool showTypeItemGrayed, NavigationBarItem memberItem, bool showMemberItemGrayed) : this(typeItem, memberItem) { ShowTypeItemGrayed = showTypeItemGrayed; ShowMemberItemGrayed = showMemberItemGrayed; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Shared/Utilities/IOUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Security; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IOUtilities { public static void PerformIO(Action action) { PerformIO<object>(() => { action(); return null; }); } public static T PerformIO<T>(Func<T> function, T defaultValue = default) { try { return function(); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static async Task<T> PerformIOAsync<T>(Func<Task<T>> function, T defaultValue = default) { try { return await function().ConfigureAwait(false); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static bool IsNormalIOException(Exception e) { return e is IOException || e is SecurityException || e is ArgumentException || e is UnauthorizedAccessException || e is NotSupportedException || e is InvalidOperationException; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Security; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IOUtilities { public static void PerformIO(Action action) { PerformIO<object>(() => { action(); return null; }); } public static T PerformIO<T>(Func<T> function, T defaultValue = default) { try { return function(); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static async Task<T> PerformIOAsync<T>(Func<Task<T>> function, T defaultValue = default) { try { return await function().ConfigureAwait(false); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static bool IsNormalIOException(Exception e) { return e is IOException || e is SecurityException || e is ArgumentException || e is UnauthorizedAccessException || e is NotSupportedException || e is InvalidOperationException; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MethodCompiler : CSharpSymbolVisitor<TypeCompilationState, object> { private readonly CSharpCompilation _compilation; private readonly bool _emittingPdb; private readonly bool _emitTestCoverageData; private readonly CancellationToken _cancellationToken; private readonly BindingDiagnosticBag _diagnostics; private readonly bool _hasDeclarationErrors; private readonly bool _emitMethodBodies; private readonly PEModuleBuilder _moduleBeingBuiltOpt; // Null if compiling for diagnostics private readonly Predicate<Symbol> _filterOpt; // If not null, limit analysis to specific symbols private readonly DebugDocumentProvider _debugDocumentProvider; private readonly SynthesizedEntryPointSymbol.AsyncForwardEntryPoint _entryPointOpt; // // MethodCompiler employs concurrency by following flattened fork/join pattern. // // For every item that we want to compile in parallel a new task is forked. // compileTaskQueue is used to track and observe all the tasks. // Once compileTaskQueue is empty, we know that there are no more tasks (and no more can be created) // and that means we are done compiling. WaitForWorkers ensures this condition. // // Note that while tasks may fork more tasks (nested types, lambdas, whatever else that may introduce more types), // we do not want any child/parent relationship between spawned tasks and their creators. // Creator has no real dependencies on the completion of its children and should finish and release any resources // as soon as it can regardless of the tasks it may have spawned. // // Stack is used so that the wait would observe the most recently added task and have // more chances to do inlined execution. private ConcurrentStack<Task> _compilerTasks; // This field tracks whether any bound method body had hasErrors set or whether any constant field had a bad value. // We track it so that we can abort emission in the event that an error occurs without a corresponding diagnostic // (e.g. if this module depends on a bad type or constant from another module). // CONSIDER: instead of storing a flag, we could track the first member symbol with an error (to improve the diagnostic). // NOTE: once the flag is set to true, it should never go back to false!!! // Do not use this as a short-circuiting for stages that might produce diagnostics. // That would make diagnostics to depend on the random order in which methods are compiled. private bool _globalHasErrors; private void SetGlobalErrorIfTrue(bool arg) { //NOTE: this is not a volatile write // for correctness we need only single threaded consistency. // Within a single task - if we have got an error it may not be safe to continue with some lowerings. // It is ok if other tasks will see the change after some delay or does not observe at all. // Such races are unavoidable and will just result in performing some work that is safe to do // but may no longer be needed. // The final Join of compiling tasks cannot happen without interlocked operations and that // will ensure that any write of the flag is globally visible. if (arg) { _globalHasErrors = true; } } // Internal for testing only. internal MethodCompiler(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool emitTestCoverageData, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate<Symbol> filterOpt, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt, CancellationToken cancellationToken) { Debug.Assert(compilation != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); Debug.Assert(diagnostics.DependenciesBag == null || diagnostics.DependenciesBag is ConcurrentSet<AssemblySymbol>); _compilation = compilation; _moduleBeingBuiltOpt = moduleBeingBuiltOpt; _emittingPdb = emittingPdb; _cancellationToken = cancellationToken; _diagnostics = diagnostics; _filterOpt = filterOpt; _entryPointOpt = entryPointOpt; _hasDeclarationErrors = hasDeclarationErrors; SetGlobalErrorIfTrue(hasDeclarationErrors); if (emittingPdb || emitTestCoverageData) { _debugDocumentProvider = (path, basePath) => moduleBeingBuiltOpt.DebugDocumentsBuilder.GetOrAddDebugDocument(path, basePath, CreateDebugDocumentForFile); } _emitTestCoverageData = emitTestCoverageData; _emitMethodBodies = emitMethodBodies; } public static void CompileMethodBodies( CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool emitTestCoverageData, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate<Symbol> filterOpt, CancellationToken cancellationToken) { Debug.Assert(compilation != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); if (compilation.PreviousSubmission != null) { // In case there is a previous submission, we should ensure // it has already created anonymous type/delegates templates // NOTE: if there are any errors, we will pick up what was created anyway compilation.PreviousSubmission.EnsureAnonymousTypeTemplates(cancellationToken); // TODO: revise to use a loop instead of a recursion } MethodSymbol entryPoint = null; if (filterOpt is null) { entryPoint = GetEntryPoint(compilation, moduleBeingBuiltOpt, hasDeclarationErrors, emitMethodBodies, diagnostics, cancellationToken); } var methodCompiler = new MethodCompiler( compilation, moduleBeingBuiltOpt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, emitMethodBodies, diagnostics, filterOpt, entryPoint as SynthesizedEntryPointSymbol.AsyncForwardEntryPoint, cancellationToken); if (compilation.Options.ConcurrentBuild) { methodCompiler._compilerTasks = new ConcurrentStack<Task>(); } // directly traverse global namespace (no point to defer this to async) methodCompiler.CompileNamespace(compilation.SourceModule.GlobalNamespace); methodCompiler.WaitForWorkers(); // compile additional and anonymous types if any if (moduleBeingBuiltOpt != null) { var additionalTypes = moduleBeingBuiltOpt.GetAdditionalTopLevelTypes(); methodCompiler.CompileSynthesizedMethods(additionalTypes, diagnostics); var embeddedTypes = moduleBeingBuiltOpt.GetEmbeddedTypes(diagnostics); methodCompiler.CompileSynthesizedMethods(embeddedTypes, diagnostics); if (emitMethodBodies) { // By this time we have processed all types reachable from module's global namespace compilation.AnonymousTypeManager.AssignTemplatesNamesAndCompile(methodCompiler, moduleBeingBuiltOpt, diagnostics); } methodCompiler.WaitForWorkers(); var privateImplClass = moduleBeingBuiltOpt.PrivateImplClass; if (privateImplClass != null) { // all threads that were adding methods must be finished now, we can freeze the class: privateImplClass.Freeze(); methodCompiler.CompileSynthesizedMethods(privateImplClass, diagnostics); } } // If we are trying to emit and there's an error without a corresponding diagnostic (e.g. because // we depend on an invalid type or constant from another module), then explicitly add a diagnostic. // This diagnostic is not very helpful to the user, but it will prevent us from emitting an invalid // module or crashing. if (moduleBeingBuiltOpt != null && (methodCompiler._globalHasErrors || moduleBeingBuiltOpt.SourceModule.HasBadAttributes) && !diagnostics.HasAnyErrors() && !hasDeclarationErrors) { var messageResourceName = methodCompiler._globalHasErrors ? nameof(CodeAnalysisResources.UnableToDetermineSpecificCauseOfFailure) : nameof(CodeAnalysisResources.ModuleHasInvalidAttributes); diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuiltOpt).Name, new LocalizableResourceString(messageResourceName, CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); } diagnostics.AddRange(compilation.AdditionalCodegenWarnings); // we can get unused field warnings only if compiling whole compilation. if (filterOpt == null) { WarnUnusedFields(compilation, diagnostics, cancellationToken); if (moduleBeingBuiltOpt != null && entryPoint != null && compilation.Options.OutputKind.IsApplication()) { moduleBeingBuiltOpt.SetPEEntryPoint(entryPoint, diagnostics.DiagnosticBag); } } } // Returns the MethodSymbol for the assembly entrypoint. If the user has a Task returning main, // this function returns the synthesized Main MethodSymbol. private static MethodSymbol GetEntryPoint(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuilt, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { Debug.Assert(diagnostics.DiagnosticBag != null); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken); Debug.Assert(!entryPointAndDiagnostics.Diagnostics.Diagnostics.IsDefault); diagnostics.AddRange(entryPointAndDiagnostics.Diagnostics, allowMismatchInDependencyAccumulation: true); var entryPoint = entryPointAndDiagnostics.MethodSymbol; if ((object)entryPoint == null) { return null; } // entryPoint can be a SynthesizedEntryPointSymbol if a script is being compiled. SynthesizedEntryPointSymbol synthesizedEntryPoint = entryPoint as SynthesizedEntryPointSymbol; if ((object)synthesizedEntryPoint == null) { var returnType = entryPoint.ReturnType; if (returnType.IsGenericTaskType(compilation) || returnType.IsNonGenericTaskType(compilation)) { synthesizedEntryPoint = new SynthesizedEntryPointSymbol.AsyncForwardEntryPoint(compilation, entryPoint.ContainingType, entryPoint); entryPoint = synthesizedEntryPoint; if ((object)moduleBeingBuilt != null) { moduleBeingBuilt.AddSynthesizedDefinition(entryPoint.ContainingType, synthesizedEntryPoint.GetCciAdapter()); } } } if (((object)synthesizedEntryPoint != null) && (moduleBeingBuilt != null) && !hasDeclarationErrors && !diagnostics.HasAnyErrors()) { BoundStatement body = synthesizedEntryPoint.CreateBody(diagnostics); if (body.HasErrors || diagnostics.HasAnyErrors()) { return entryPoint; } var dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; VariableSlotAllocator lazyVariableSlotAllocator = null; var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); StateMachineTypeSymbol stateMachineTypeOpt = null; const int methodOrdinal = -1; var loweredBody = LowerBodyOrInitializer( synthesizedEntryPoint, methodOrdinal, body, null, new TypeCompilationState(synthesizedEntryPoint.ContainingType, compilation, moduleBeingBuilt), false, null, ref dynamicAnalysisSpans, diagnostics, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out stateMachineTypeOpt); Debug.Assert((object)lazyVariableSlotAllocator == null); Debug.Assert((object)stateMachineTypeOpt == null); Debug.Assert(dynamicAnalysisSpans.IsEmpty); Debug.Assert(lambdaDebugInfoBuilder.IsEmpty()); Debug.Assert(closureDebugInfoBuilder.IsEmpty()); lambdaDebugInfoBuilder.Free(); closureDebugInfoBuilder.Free(); if (emitMethodBodies) { var emittedBody = GenerateMethodBody( moduleBeingBuilt, synthesizedEntryPoint, methodOrdinal, loweredBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachineTypeOpt: null, variableSlotAllocatorOpt: null, diagnostics: diagnostics, debugDocumentProvider: null, importChainOpt: null, emittingPdb: false, emitTestCoverageData: false, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, entryPointOpt: null); moduleBeingBuilt.SetMethodBody(synthesizedEntryPoint, emittedBody); } } return entryPoint; } private void WaitForWorkers() { var tasks = _compilerTasks; if (tasks == null) { return; } Task curTask; while (tasks.TryPop(out curTask)) { curTask.GetAwaiter().GetResult(); } } private static void WarnUnusedFields(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { SourceAssemblySymbol assembly = (SourceAssemblySymbol)compilation.Assembly; diagnostics.AddRange(assembly.GetUnusedFieldWarnings(cancellationToken)); } public override object VisitNamespace(NamespaceSymbol symbol, TypeCompilationState arg) { if (!PassesFilter(_filterOpt, symbol)) { return null; } arg = null; // do not use compilation state of outer type. _cancellationToken.ThrowIfCancellationRequested(); if (_compilation.Options.ConcurrentBuild) { Task worker = CompileNamespaceAsAsync(symbol); _compilerTasks.Push(worker); } else { CompileNamespace(symbol); } return null; } private Task CompileNamespaceAsAsync(NamespaceSymbol symbol) { return Task.Run(UICultureUtilities.WithCurrentUICulture(() => { try { CompileNamespace(symbol); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }), _cancellationToken); } private void CompileNamespace(NamespaceSymbol symbol) { foreach (var s in symbol.GetMembersUnordered()) { s.Accept(this, null); } } public override object VisitNamedType(NamedTypeSymbol symbol, TypeCompilationState arg) { if (!PassesFilter(_filterOpt, symbol)) { return null; } arg = null; // do not use compilation state of outer type. _cancellationToken.ThrowIfCancellationRequested(); if (_compilation.Options.ConcurrentBuild) { Task worker = CompileNamedTypeAsync(symbol); _compilerTasks.Push(worker); } else { CompileNamedType(symbol); } return null; } private Task CompileNamedTypeAsync(NamedTypeSymbol symbol) { return Task.Run(UICultureUtilities.WithCurrentUICulture(() => { try { CompileNamedType(symbol); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }), _cancellationToken); } private void CompileNamedType(NamedTypeSymbol containingType) { var compilationState = new TypeCompilationState(containingType, _compilation, _moduleBeingBuiltOpt); _cancellationToken.ThrowIfCancellationRequested(); // Find the constructor of a script class. SynthesizedInstanceConstructor scriptCtor = null; SynthesizedInteractiveInitializerMethod scriptInitializer = null; SynthesizedEntryPointSymbol scriptEntryPoint = null; int scriptCtorOrdinal = -1; if (containingType.IsScriptClass) { // The field initializers of a script class could be arbitrary statements, // including blocks. Field initializers containing blocks need to // use a MethodBodySemanticModel to build up the appropriate tree of binders, and // MethodBodySemanticModel requires an "owning" method. That's why we're digging out // the constructor - it will own the field initializers. scriptCtor = containingType.GetScriptConstructor(); scriptInitializer = containingType.GetScriptInitializer(); scriptEntryPoint = containingType.GetScriptEntryPoint(); Debug.Assert((object)scriptCtor != null); Debug.Assert((object)scriptInitializer != null); } var synthesizedSubmissionFields = containingType.IsSubmissionClass ? new SynthesizedSubmissionFields(_compilation, containingType) : null; var processedStaticInitializers = new Binder.ProcessedFieldInitializers(); var processedInstanceInitializers = new Binder.ProcessedFieldInitializers(); var sourceTypeSymbol = containingType as SourceMemberContainerTypeSymbol; if ((object)sourceTypeSymbol != null) { _cancellationToken.ThrowIfCancellationRequested(); Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.StaticInitializers, _diagnostics, ref processedStaticInitializers); _cancellationToken.ThrowIfCancellationRequested(); Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.InstanceInitializers, _diagnostics, ref processedInstanceInitializers); if (compilationState.Emitting) { CompileSynthesizedExplicitImplementations(sourceTypeSymbol, compilationState); } } // Indicates if a static constructor is in the member, // so we can decide to synthesize a static constructor. bool hasStaticConstructor = false; var members = containingType.GetMembers(); for (int memberOrdinal = 0; memberOrdinal < members.Length; memberOrdinal++) { var member = members[memberOrdinal]; //When a filter is supplied, limit the compilation of members passing the filter. if (!PassesFilter(_filterOpt, member)) { continue; } switch (member.Kind) { case SymbolKind.NamedType: member.Accept(this, compilationState); break; case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; if (method.IsScriptConstructor) { Debug.Assert(scriptCtorOrdinal == -1); Debug.Assert((object)scriptCtor == method); scriptCtorOrdinal = memberOrdinal; continue; } if ((object)method == scriptEntryPoint) { continue; } if (IsFieldLikeEventAccessor(method)) { continue; } if (method.IsPartialDefinition()) { method = method.PartialImplementationPart; if ((object)method == null) { continue; } } Binder.ProcessedFieldInitializers processedInitializers = (method.MethodKind == MethodKind.Constructor || method.IsScriptInitializer) ? processedInstanceInitializers : method.MethodKind == MethodKind.StaticConstructor ? processedStaticInitializers : default(Binder.ProcessedFieldInitializers); CompileMethod(method, memberOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState); // Set a flag to indicate that a static constructor is created. if (method.MethodKind == MethodKind.StaticConstructor) { hasStaticConstructor = true; } break; } case SymbolKind.Property: { var sourceProperty = member as SourcePropertySymbolBase; if ((object)sourceProperty != null && sourceProperty.IsSealed && compilationState.Emitting) { CompileSynthesizedSealedAccessors(sourceProperty, compilationState); } break; } case SymbolKind.Event: { SourceEventSymbol eventSymbol = member as SourceEventSymbol; if ((object)eventSymbol != null && eventSymbol.HasAssociatedField && !eventSymbol.IsAbstract && compilationState.Emitting) { CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: true); CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: false); } break; } case SymbolKind.Field: { var fieldSymbol = (FieldSymbol)member; if (member is TupleErrorFieldSymbol) { break; } if (fieldSymbol.IsConst) { // We check specifically for constant fields with bad values because they never result // in bound nodes being inserted into method bodies (in which case, they would be covered // by the method-level check). ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); SetGlobalErrorIfTrue(constantValue == null || constantValue.IsBad); } if (fieldSymbol.IsFixedSizeBuffer && compilationState.Emitting) { // force the generation of implementation types for fixed-size buffers TypeSymbol discarded = fieldSymbol.FixedImplementationType(compilationState.ModuleBuilderOpt); } break; } } } Debug.Assert(containingType.IsScriptClass == (scriptCtorOrdinal >= 0)); // process additional anonymous type members if (AnonymousTypeManager.IsAnonymousTypeTemplate(containingType)) { var processedInitializers = default(Binder.ProcessedFieldInitializers); foreach (var method in AnonymousTypeManager.GetAnonymousTypeHiddenMethods(containingType)) { CompileMethod(method, -1, ref processedInitializers, synthesizedSubmissionFields, compilationState); } } // In the case there are field initializers but we haven't created an implicit static constructor (.cctor) for it, // (since we may not add .cctor implicitly created for decimals into the symbol table) // it is necessary for the compiler to generate the static constructor here if we are emitting. if (_moduleBeingBuiltOpt != null && !hasStaticConstructor && !processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty) { Debug.Assert(processedStaticInitializers.BoundInitializers.All((init) => (init.Kind == BoundKind.FieldEqualsValue) && !((BoundFieldEqualsValue)init).Field.IsMetadataConstant)); MethodSymbol method = new SynthesizedStaticConstructor(sourceTypeSymbol); if (PassesFilter(_filterOpt, method)) { CompileMethod(method, -1, ref processedStaticInitializers, synthesizedSubmissionFields, compilationState); // If this method has been successfully built, we emit it. if (_moduleBeingBuiltOpt.GetMethodBody(method) != null) { _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, method.GetCciAdapter()); } } } // If there is no explicit or implicit .cctor and no static initializers, then report // warnings for any static non-nullable fields. (If there is no .cctor, there // shouldn't be any initializers but for robustness, we check both.) if (!hasStaticConstructor && processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty && _compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion() && containingType is { IsImplicitlyDeclared: false, TypeKind: TypeKind.Class or TypeKind.Struct or TypeKind.Interface }) { NullableWalker.AnalyzeIfNeeded( this._compilation, new SynthesizedStaticConstructor(containingType), GetSynthesizedEmptyBody(containingType), _diagnostics.DiagnosticBag, useConstructorExitWarnings: true, initialNullableState: null, getFinalNullableState: false, finalNullableState: out _); } // compile submission constructor last so that synthesized submission fields are collected from all script methods: if (scriptCtor != null && compilationState.Emitting) { Debug.Assert(scriptCtorOrdinal >= 0); var processedInitializers = new Binder.ProcessedFieldInitializers() { BoundInitializers = ImmutableArray<BoundInitializer>.Empty }; CompileMethod(scriptCtor, scriptCtorOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState); if (synthesizedSubmissionFields != null) { synthesizedSubmissionFields.AddToType(containingType, compilationState.ModuleBuilderOpt); } } // Emit synthesized methods produced during lowering if any if (_moduleBeingBuiltOpt != null) { CompileSynthesizedMethods(compilationState); } compilationState.Free(); } private void CompileSynthesizedMethods(PrivateImplementationDetails privateImplClass, BindingDiagnosticBag diagnostics) { Debug.Assert(_moduleBeingBuiltOpt != null); var compilationState = new TypeCompilationState(null, _compilation, _moduleBeingBuiltOpt); foreach (Cci.IMethodDefinition definition in privateImplClass.GetMethods(new EmitContext(_moduleBeingBuiltOpt, null, diagnostics.DiagnosticBag, metadataOnly: false, includePrivateMembers: true))) { var method = (MethodSymbol)definition.GetInternalSymbol(); Debug.Assert(method.SynthesizesLoweredBoundBody); method.GenerateMethodBody(compilationState, diagnostics); } CompileSynthesizedMethods(compilationState); compilationState.Free(); } private void CompileSynthesizedMethods(ImmutableArray<NamedTypeSymbol> additionalTypes, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag != null); foreach (var additionalType in additionalTypes) { var compilationState = new TypeCompilationState(additionalType, _compilation, _moduleBeingBuiltOpt); foreach (var method in additionalType.GetMethodsToEmit()) { method.GenerateMethodBody(compilationState, diagnostics); } if (!diagnostics.HasAnyErrors()) { CompileSynthesizedMethods(compilationState); } compilationState.Free(); } } private void CompileSynthesizedMethods(TypeCompilationState compilationState) { Debug.Assert(_moduleBeingBuiltOpt != null); Debug.Assert(compilationState.ModuleBuilderOpt == _moduleBeingBuiltOpt); var synthesizedMethods = compilationState.SynthesizedMethods; if (synthesizedMethods == null) { return; } var oldImportChain = compilationState.CurrentImportChain; try { foreach (var methodWithBody in synthesizedMethods) { var importChain = methodWithBody.ImportChain; compilationState.CurrentImportChain = importChain; // We make sure that an asynchronous mutation to the diagnostic bag does not // confuse the method body generator by making a fresh bag and then loading // any diagnostics emitted into it back into the main diagnostic bag. var diagnosticsThisMethod = BindingDiagnosticBag.GetInstance(_diagnostics); var method = methodWithBody.Method; var lambda = method as SynthesizedClosureMethod; var variableSlotAllocatorOpt = ((object)lambda != null) ? _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(lambda, lambda.TopLevelMethod, diagnosticsThisMethod.DiagnosticBag) : _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(method, method, diagnosticsThisMethod.DiagnosticBag); // Synthesized methods have no ordinal stored in custom debug information (only user-defined methods have ordinals). // In case of async lambdas, which synthesize a state machine type during the following rewrite, the containing method has already been uniquely named, // so there is no need to produce a unique method ordinal for the corresponding state machine type, whose name includes the (unique) containing method name. const int methodOrdinal = -1; MethodBody emittedBody = null; try { // Local functions can be iterators as well as be async (lambdas can only be async), so we need to lower both iterators and async IteratorStateMachine iteratorStateMachine; BoundStatement loweredBody = IteratorRewriter.Rewrite(methodWithBody.Body, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out iteratorStateMachine); StateMachineTypeSymbol stateMachine = iteratorStateMachine; if (!loweredBody.HasErrors) { AsyncStateMachine asyncStateMachine; loweredBody = AsyncRewriter.Rewrite(loweredBody, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out asyncStateMachine); Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null); stateMachine = stateMachine ?? asyncStateMachine; } if (_emitMethodBodies && !diagnosticsThisMethod.HasAnyErrors() && !_globalHasErrors) { emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, method, methodOrdinal, loweredBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachine, variableSlotAllocatorOpt, diagnosticsThisMethod, _debugDocumentProvider, method.GenerateDebugInfo ? importChain : null, emittingPdb: _emittingPdb, emitTestCoverageData: _emitTestCoverageData, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, _entryPointOpt); } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(_diagnostics); } _diagnostics.AddRange(diagnosticsThisMethod); diagnosticsThisMethod.Free(); if (_emitMethodBodies) { // error while generating IL if (emittedBody == null) { break; } _moduleBeingBuiltOpt.SetMethodBody(method, emittedBody); } else { Debug.Assert(emittedBody is null); } } } finally { compilationState.CurrentImportChain = oldImportChain; } } private static bool IsFieldLikeEventAccessor(MethodSymbol method) { Symbol associatedPropertyOrEvent = method.AssociatedSymbol; return (object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event && ((EventSymbol)associatedPropertyOrEvent).HasAssociatedField; } /// <summary> /// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a /// base type from another assembly) it is necessary for the compiler to generate explicit implementations for /// some interface methods. They don't go in the symbol table, but if we are emitting, then we should /// generate code for them. /// </summary> private void CompileSynthesizedExplicitImplementations(SourceMemberContainerTypeSymbol sourceTypeSymbol, TypeCompilationState compilationState) { // we are not generating any observable diagnostics here so it is ok to short-circuit on global errors. if (!_globalHasErrors) { var discardedDiagnostics = BindingDiagnosticBag.GetInstance(_diagnostics); foreach (var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods) { Debug.Assert(synthesizedExplicitImpl.SynthesizesLoweredBoundBody); synthesizedExplicitImpl.GenerateMethodBody(compilationState, discardedDiagnostics); Debug.Assert(!discardedDiagnostics.HasAnyErrors()); discardedDiagnostics.DiagnosticBag.Clear(); _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, synthesizedExplicitImpl.GetCciAdapter()); } _diagnostics.AddRangeAndFree(discardedDiagnostics); } } private void CompileSynthesizedSealedAccessors(SourcePropertySymbolBase sourceProperty, TypeCompilationState compilationState) { SynthesizedSealedPropertyAccessor synthesizedAccessor = sourceProperty.SynthesizedSealedAccessorOpt; // we are not generating any observable diagnostics here so it is ok to short-circuit on global errors. if ((object)synthesizedAccessor != null && !_globalHasErrors) { Debug.Assert(synthesizedAccessor.SynthesizesLoweredBoundBody); var discardedDiagnostics = BindingDiagnosticBag.GetInstance(_diagnostics); synthesizedAccessor.GenerateMethodBody(compilationState, discardedDiagnostics); Debug.Assert(!discardedDiagnostics.HasAnyErrors()); _diagnostics.AddDependencies(discardedDiagnostics); discardedDiagnostics.Free(); _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceProperty.ContainingType, synthesizedAccessor.GetCciAdapter()); } } private void CompileFieldLikeEventAccessor(SourceEventSymbol eventSymbol, bool isAddMethod) { MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; var diagnosticsThisMethod = BindingDiagnosticBag.GetInstance(_diagnostics); try { BoundBlock boundBody = MethodBodySynthesizer.ConstructFieldLikeEventAccessorBody(eventSymbol, isAddMethod, _compilation, diagnosticsThisMethod); var hasErrors = diagnosticsThisMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); // we cannot rely on GlobalHasErrors since that can be changed concurrently by other methods compiling // we however do not want to continue with generating method body if we have errors in this particular method - generating may crash // or if had declaration errors - we will fail anyways, but if some types are bad enough, generating may produce duplicate errors about that. if (!hasErrors && !_hasDeclarationErrors && _emitMethodBodies) { const int accessorOrdinal = -1; MethodBody emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, accessor, accessorOrdinal, boundBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachineTypeOpt: null, variableSlotAllocatorOpt: null, diagnostics: diagnosticsThisMethod, debugDocumentProvider: _debugDocumentProvider, importChainOpt: null, emittingPdb: false, emitTestCoverageData: _emitTestCoverageData, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, entryPointOpt: null); _moduleBeingBuiltOpt.SetMethodBody(accessor, emittedBody); // Definition is already in the symbol table, so don't call moduleBeingBuilt.AddCompilerGeneratedDefinition } } finally { _diagnostics.AddRange(diagnosticsThisMethod); diagnosticsThisMethod.Free(); } } public override object VisitMethod(MethodSymbol symbol, TypeCompilationState arg) { throw ExceptionUtilities.Unreachable; } public override object VisitProperty(PropertySymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } public override object VisitEvent(EventSymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } public override object VisitField(FieldSymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } private void CompileMethod( MethodSymbol methodSymbol, int methodOrdinal, ref Binder.ProcessedFieldInitializers processedInitializers, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState) { _cancellationToken.ThrowIfCancellationRequested(); SourceMemberMethodSymbol sourceMethod = methodSymbol as SourceMemberMethodSymbol; if (methodSymbol.IsAbstract || methodSymbol.ContainingType?.IsDelegateType() == true) { if ((object)sourceMethod != null) { bool diagsWritten; sourceMethod.SetDiagnostics(ImmutableArray<Diagnostic>.Empty, out diagsWritten); if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null) { _compilation.SymbolDeclaredEvent(methodSymbol); } } return; } // get cached diagnostics if not building and we have 'em if (_moduleBeingBuiltOpt == null && (object)sourceMethod != null) { var cachedDiagnostics = sourceMethod.Diagnostics; if (!cachedDiagnostics.IsDefault) { _diagnostics.AddRange(cachedDiagnostics); return; } } ImportChain oldImportChain = compilationState.CurrentImportChain; // In order to avoid generating code for methods with errors, we create a diagnostic bag just for this method. var diagsForCurrentMethod = BindingDiagnosticBag.GetInstance(_diagnostics); try { // if synthesized method returns its body in lowered form if (methodSymbol.SynthesizesLoweredBoundBody) { if (_moduleBeingBuiltOpt != null) { methodSymbol.GenerateMethodBody(compilationState, diagsForCurrentMethod); _diagnostics.AddRange(diagsForCurrentMethod); } return; } // no need to emit the default ctor, we are not emitting those if (methodSymbol.IsDefaultValueTypeConstructor()) { return; } bool includeNonEmptyInitializersInBody = false; BoundBlock body; bool originalBodyNested = false; // initializers that have been analyzed but not yet lowered. BoundStatementList analyzedInitializers = null; MethodBodySemanticModel.InitialState forSemanticModel = default; ImportChain importChain = null; var hasTrailingExpression = false; if (methodSymbol.IsScriptConstructor) { Debug.Assert(methodSymbol.IsImplicitlyDeclared); body = new BoundBlock(methodSymbol.GetNonNullSyntaxNode(), ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty) { WasCompilerGenerated = true }; } else if (methodSymbol.IsScriptInitializer) { Debug.Assert(methodSymbol.IsImplicitlyDeclared); // rewrite top-level statements and script variable declarations to a list of statements and assignments, respectively: var initializerStatements = InitializerRewriter.RewriteScriptInitializer(processedInitializers.BoundInitializers, (SynthesizedInteractiveInitializerMethod)methodSymbol, out hasTrailingExpression); // the lowered script initializers should not be treated as initializers anymore but as a method body: body = BoundBlock.SynthesizedNoLocals(initializerStatements.Syntax, initializerStatements.Statements); NullableWalker.AnalyzeIfNeeded( _compilation, methodSymbol, initializerStatements, diagsForCurrentMethod.DiagnosticBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out processedInitializers.AfterInitializersState); var unusedDiagnostics = DiagnosticBag.GetInstance(); DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, initializerStatements, unusedDiagnostics, requireOutParamsAssigned: false); DiagnosticsPass.IssueDiagnostics(_compilation, initializerStatements, BindingDiagnosticBag.Discarded, methodSymbol); unusedDiagnostics.Free(); } else { var includeInitializersInBody = methodSymbol.IncludeFieldInitializersInBody(); // Do not emit initializers if we are invoking another constructor of this class. includeNonEmptyInitializersInBody = includeInitializersInBody && !processedInitializers.BoundInitializers.IsDefaultOrEmpty; if (includeNonEmptyInitializersInBody && processedInitializers.LoweredInitializers == null) { analyzedInitializers = InitializerRewriter.RewriteConstructor(processedInitializers.BoundInitializers, methodSymbol); processedInitializers.HasErrors = processedInitializers.HasErrors || analyzedInitializers.HasAnyErrors; } if (includeInitializersInBody && processedInitializers.AfterInitializersState is null) { NullableWalker.AnalyzeIfNeeded( _compilation, methodSymbol, // we analyze to produce an AfterInitializersState even if there are no initializers // because it conveniently allows us to capture all the 'default' states for applicable members analyzedInitializers ?? GetSynthesizedEmptyBody(methodSymbol), diagsForCurrentMethod.DiagnosticBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out processedInitializers.AfterInitializersState); } body = BindMethodBody(methodSymbol, compilationState, diagsForCurrentMethod, processedInitializers.AfterInitializersState, out importChain, out originalBodyNested, out forSemanticModel); if (diagsForCurrentMethod.HasAnyErrors() && body != null) { body = (BoundBlock)body.WithHasErrors(); } // lower initializers just once. the lowered tree will be reused when emitting all constructors // with field initializers. Once lowered, these initializers will be stashed in processedInitializers.LoweredInitializers // (see later in this method). Don't bother lowering _now_ if this particular ctor won't have the initializers // appended to its body. if (includeNonEmptyInitializersInBody && processedInitializers.LoweredInitializers == null) { if (body != null && ((methodSymbol.ContainingType.IsStructType() && !methodSymbol.IsImplicitConstructor) || methodSymbol is SynthesizedRecordConstructor || _emitTestCoverageData)) { if (_emitTestCoverageData && methodSymbol.IsImplicitConstructor) { // Flow analysis over the initializers is necessary in order to find assignments to fields. // Bodies of implicit constructors do not get flow analysis later, so the initializers // are analyzed here. DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod.DiagnosticBag, requireOutParamsAssigned: false); } // In order to get correct diagnostics, we need to analyze initializers and the body together. body = body.Update(body.Locals, body.LocalFunctions, body.Statements.Insert(0, analyzedInitializers)); includeNonEmptyInitializersInBody = false; analyzedInitializers = null; } else { // These analyses check for diagnostics in lambdas. // Control flow analysis and implicit return insertion are unnecessary. DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod.DiagnosticBag, requireOutParamsAssigned: false); DiagnosticsPass.IssueDiagnostics(_compilation, analyzedInitializers, diagsForCurrentMethod, methodSymbol); } } } #if DEBUG // If the method is a synthesized static or instance constructor, then debugImports will be null and we will use the value // from the first field initializer. if ((methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) && methodSymbol.IsImplicitlyDeclared && body == null) { // There was no body to bind, so we didn't get anything from BindMethodBody. Debug.Assert(importChain == null); } // Either there were no field initializers or we grabbed debug imports from the first one. Debug.Assert(processedInitializers.BoundInitializers.IsDefaultOrEmpty || processedInitializers.FirstImportChain != null); #endif importChain = importChain ?? processedInitializers.FirstImportChain; // Associate these debug imports with all methods generated from this one. compilationState.CurrentImportChain = importChain; if (body != null) { DiagnosticsPass.IssueDiagnostics(_compilation, body, diagsForCurrentMethod, methodSymbol); } BoundBlock flowAnalyzedBody = null; if (body != null) { flowAnalyzedBody = FlowAnalysisPass.Rewrite(methodSymbol, body, diagsForCurrentMethod.DiagnosticBag, hasTrailingExpression: hasTrailingExpression, originalBodyNested: originalBodyNested); } bool hasErrors = _hasDeclarationErrors || diagsForCurrentMethod.HasAnyErrors() || processedInitializers.HasErrors; // Record whether or not the bound tree for the lowered method body (including any initializers) contained any // errors (note: errors, not diagnostics). SetGlobalErrorIfTrue(hasErrors); bool diagsWritten = false; var actualDiagnostics = diagsForCurrentMethod.ToReadOnly(); if (sourceMethod != null) { actualDiagnostics = new ImmutableBindingDiagnostic<AssemblySymbol>(sourceMethod.SetDiagnostics(actualDiagnostics.Diagnostics, out diagsWritten), actualDiagnostics.Dependencies); } if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null) { // If compilation has a caching semantic model provider, then cache the already-computed bound tree // onto the semantic model and store it on the event. SyntaxTreeSemanticModel semanticModelWithCachedBoundNodes = null; if (body != null && forSemanticModel.Syntax is { } semanticModelSyntax && _compilation.SemanticModelProvider is CachingSemanticModelProvider cachingSemanticModelProvider) { var syntax = body.Syntax; semanticModelWithCachedBoundNodes = (SyntaxTreeSemanticModel)cachingSemanticModelProvider.GetSemanticModel(syntax.SyntaxTree, _compilation); semanticModelWithCachedBoundNodes.GetOrAddModel(semanticModelSyntax, (rootSyntax) => { Debug.Assert(rootSyntax == forSemanticModel.Syntax); return MethodBodySemanticModel.Create(semanticModelWithCachedBoundNodes, methodSymbol, forSemanticModel); }); } _compilation.EventQueue.TryEnqueue(new SymbolDeclaredCompilationEvent(_compilation, methodSymbol.GetPublicSymbol(), semanticModelWithCachedBoundNodes)); } // Don't lower if we're not emitting or if there were errors. // Methods that had binding errors are considered too broken to be lowered reliably. if (_moduleBeingBuiltOpt == null || hasErrors) { _diagnostics.AddRange(actualDiagnostics); return; } // ############################ // LOWERING AND EMIT // Any errors generated below here are considered Emit diagnostics // and will not be reported to callers Compilation.GetDiagnostics() ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; bool hasBody = flowAnalyzedBody != null; VariableSlotAllocator lazyVariableSlotAllocator = null; StateMachineTypeSymbol stateMachineTypeOpt = null; var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); BoundStatement loweredBodyOpt = null; try { if (hasBody) { loweredBodyOpt = LowerBodyOrInitializer( methodSymbol, methodOrdinal, flowAnalyzedBody, previousSubmissionFields, compilationState, _emitTestCoverageData, _debugDocumentProvider, ref dynamicAnalysisSpans, diagsForCurrentMethod, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out stateMachineTypeOpt); Debug.Assert(loweredBodyOpt != null); } else { loweredBodyOpt = null; } hasErrors = hasErrors || (hasBody && loweredBodyOpt.HasErrors) || diagsForCurrentMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); // don't emit if the resulting method would contain initializers with errors if (!hasErrors && (hasBody || includeNonEmptyInitializersInBody)) { Debug.Assert(!(methodSymbol.IsImplicitInstanceConstructor && methodSymbol.ParameterCount == 0) || !methodSymbol.ContainingType.IsStructType()); // Fields must be initialized before constructor initializer (which is the first statement of the analyzed body, if specified), // so that the initialization occurs before any method overridden by the declaring class can be invoked from the base constructor // and access the fields. ImmutableArray<BoundStatement> boundStatements; if (methodSymbol.IsScriptConstructor) { boundStatements = MethodBodySynthesizer.ConstructScriptConstructorBody(loweredBodyOpt, methodSymbol, previousSubmissionFields, _compilation); } else { boundStatements = ImmutableArray<BoundStatement>.Empty; if (analyzedInitializers != null) { // For dynamic analysis, field initializers are instrumented as part of constructors, // and so are never instrumented here. Debug.Assert(!_emitTestCoverageData); StateMachineTypeSymbol initializerStateMachineTypeOpt; BoundStatement lowered = LowerBodyOrInitializer( methodSymbol, methodOrdinal, analyzedInitializers, previousSubmissionFields, compilationState, _emitTestCoverageData, _debugDocumentProvider, ref dynamicAnalysisSpans, diagsForCurrentMethod, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out initializerStateMachineTypeOpt); processedInitializers.LoweredInitializers = lowered; // initializers can't produce state machines Debug.Assert((object)initializerStateMachineTypeOpt == null); Debug.Assert(!hasErrors); hasErrors = lowered.HasAnyErrors || diagsForCurrentMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); if (hasErrors) { _diagnostics.AddRange(diagsForCurrentMethod); return; } // Only do the cast if we haven't returned with some error diagnostics. // Otherwise, `lowered` might have been a BoundBadStatement. processedInitializers.LoweredInitializers = (BoundStatementList)lowered; } // initializers for global code have already been included in the body if (includeNonEmptyInitializersInBody) { if (processedInitializers.LoweredInitializers.Kind == BoundKind.StatementList) { BoundStatementList lowered = (BoundStatementList)processedInitializers.LoweredInitializers; boundStatements = boundStatements.Concat(lowered.Statements); } else { boundStatements = boundStatements.Add(processedInitializers.LoweredInitializers); } } if (hasBody) { boundStatements = boundStatements.Concat(ImmutableArray.Create(loweredBodyOpt)); } } if (_emitMethodBodies && (!(methodSymbol is SynthesizedStaticConstructor cctor) || cctor.ShouldEmit(processedInitializers.BoundInitializers))) { CSharpSyntaxNode syntax = methodSymbol.GetNonNullSyntaxNode(); var boundBody = BoundStatementList.Synthesized(syntax, boundStatements); var emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, methodSymbol, methodOrdinal, boundBody, lambdaDebugInfoBuilder.ToImmutable(), closureDebugInfoBuilder.ToImmutable(), stateMachineTypeOpt, lazyVariableSlotAllocator, diagsForCurrentMethod, _debugDocumentProvider, importChain, _emittingPdb, _emitTestCoverageData, dynamicAnalysisSpans, entryPointOpt: null); _moduleBeingBuiltOpt.SetMethodBody(methodSymbol.PartialDefinitionPart ?? methodSymbol, emittedBody); } } _diagnostics.AddRange(diagsForCurrentMethod); } finally { lambdaDebugInfoBuilder.Free(); closureDebugInfoBuilder.Free(); } } finally { diagsForCurrentMethod.Free(); compilationState.CurrentImportChain = oldImportChain; } } // internal for testing internal static BoundStatement LowerBodyOrInitializer( MethodSymbol method, int methodOrdinal, BoundStatement body, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState, bool instrumentForDynamicAnalysis, DebugDocumentProvider debugDocumentProvider, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, BindingDiagnosticBag diagnostics, ref VariableSlotAllocator lazyVariableSlotAllocator, ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder, ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder, out StateMachineTypeSymbol stateMachineTypeOpt) { Debug.Assert(compilationState.ModuleBuilderOpt != null); stateMachineTypeOpt = null; if (body.HasErrors) { return body; } try { var loweredBody = LocalRewriter.Rewrite( method.DeclaringCompilation, method, methodOrdinal, method.ContainingType, body, compilationState, previousSubmissionFields: previousSubmissionFields, allowOmissionOfConditionalCalls: true, instrumentForDynamicAnalysis: instrumentForDynamicAnalysis, debugDocumentProvider: debugDocumentProvider, dynamicAnalysisSpans: ref dynamicAnalysisSpans, diagnostics: diagnostics, sawLambdas: out bool sawLambdas, sawLocalFunctions: out bool sawLocalFunctions, sawAwaitInExceptionHandler: out bool sawAwaitInExceptionHandler); if (loweredBody.HasErrors) { return loweredBody; } if (sawAwaitInExceptionHandler) { // If we have awaits in handlers, we need to // replace handlers with synthetic ones which can be consumed by async rewriter. // The reason why this rewrite happens before the lambda rewrite // is that we may need access to exception locals and it would be fairly hard to do // if these locals are captured into closures (possibly nested ones). loweredBody = AsyncExceptionHandlerRewriter.Rewrite( method, method.ContainingType, loweredBody, compilationState, diagnostics); } if (loweredBody.HasErrors) { return loweredBody; } if (lazyVariableSlotAllocator == null) { lazyVariableSlotAllocator = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method, method, diagnostics.DiagnosticBag); } BoundStatement bodyWithoutLambdas = loweredBody; if (sawLambdas || sawLocalFunctions) { bodyWithoutLambdas = ClosureConversion.Rewrite( loweredBody, method.ContainingType, method.ThisParameter, method, methodOrdinal, null, lambdaDebugInfoBuilder, closureDebugInfoBuilder, lazyVariableSlotAllocator, compilationState, diagnostics, assignLocals: null); } if (bodyWithoutLambdas.HasErrors) { return bodyWithoutLambdas; } BoundStatement bodyWithoutIterators = IteratorRewriter.Rewrite(bodyWithoutLambdas, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics, out IteratorStateMachine iteratorStateMachine); if (bodyWithoutIterators.HasErrors) { return bodyWithoutIterators; } BoundStatement bodyWithoutAsync = AsyncRewriter.Rewrite(bodyWithoutIterators, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics, out AsyncStateMachine asyncStateMachine); Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null); stateMachineTypeOpt = (StateMachineTypeSymbol)iteratorStateMachine ?? asyncStateMachine; return bodyWithoutAsync; } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); return new BoundBadStatement(body.Syntax, ImmutableArray.Create<BoundNode>(body), hasErrors: true); } } /// <summary> /// entryPointOpt is only considered for synthesized methods (to recognize the synthesized MoveNext method for async Main) /// </summary> private static MethodBody GenerateMethodBody( PEModuleBuilder moduleBuilder, MethodSymbol method, int methodOrdinal, BoundStatement block, ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, StateMachineTypeSymbol stateMachineTypeOpt, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, DebugDocumentProvider debugDocumentProvider, ImportChain importChainOpt, bool emittingPdb, bool emitTestCoverageData, ImmutableArray<SourceSpan> dynamicAnalysisSpans, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt) { // Note: don't call diagnostics.HasAnyErrors() in release; could be expensive if compilation has many warnings. Debug.Assert(!diagnostics.HasAnyErrors(), "Running code generator when errors exist might be dangerous; code generator not expecting errors"); var compilation = moduleBuilder.Compilation; var localSlotManager = new LocalSlotManager(variableSlotAllocatorOpt); var optimizations = compilation.Options.OptimizationLevel; ILBuilder builder = new ILBuilder(moduleBuilder, localSlotManager, optimizations, method.AreLocalsZeroed); bool hasStackalloc; var diagnosticsForThisMethod = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); try { StateMachineMoveNextBodyDebugInfo moveNextBodyDebugInfoOpt = null; var codeGen = new CodeGen.CodeGenerator(method, block, builder, moduleBuilder, diagnosticsForThisMethod.DiagnosticBag, optimizations, emittingPdb); if (diagnosticsForThisMethod.HasAnyErrors()) { // we are done here. Since there were errors we should not emit anything. return null; } bool isAsyncStateMachine; MethodSymbol kickoffMethod; if (method is SynthesizedStateMachineMethod stateMachineMethod && method.Name == WellKnownMemberNames.MoveNextMethodName) { kickoffMethod = stateMachineMethod.StateMachineType.KickoffMethod; Debug.Assert(kickoffMethod != null); isAsyncStateMachine = kickoffMethod.IsAsync; // Async void method may be partial. Debug info needs to be associated with the emitted definition, // but the kickoff method is the method implementation (the part with body). kickoffMethod = kickoffMethod.PartialDefinitionPart ?? kickoffMethod; } else { kickoffMethod = null; isAsyncStateMachine = false; } if (isAsyncStateMachine) { codeGen.Generate(out int asyncCatchHandlerOffset, out var asyncYieldPoints, out var asyncResumePoints, out hasStackalloc); // The exception handler IL offset is used by the debugger to treat exceptions caught by the marked catch block as "user unhandled". // This is important for async void because async void exceptions generally result in the process being terminated, // but without anything useful on the call stack. Async Task methods on the other hand return exceptions as the result of the Task. // So it is undesirable to consider these exceptions "user unhandled" since there may well be user code that is awaiting the task. // This is a heuristic since it's possible that there is no user code awaiting the task. // We do the same for async Main methods, since it is unlikely that user code will be awaiting the Task: // AsyncForwardEntryPoint <Main> -> kick-off method Main -> MoveNext. bool isAsyncMainMoveNext = entryPointOpt?.UserMain.Equals(kickoffMethod) == true; moveNextBodyDebugInfoOpt = new AsyncMoveNextBodyDebugInfo( kickoffMethod.GetCciAdapter(), catchHandlerOffset: (kickoffMethod.ReturnsVoid || isAsyncMainMoveNext) ? asyncCatchHandlerOffset : -1, asyncYieldPoints, asyncResumePoints); } else { codeGen.Generate(out hasStackalloc); if ((object)kickoffMethod != null) { moveNextBodyDebugInfoOpt = new IteratorMoveNextBodyDebugInfo(kickoffMethod.GetCciAdapter()); } } // Compiler-generated MoveNext methods have hoisted local scopes. // These are built by call to CodeGen.Generate. var stateMachineHoistedLocalScopes = ((object)kickoffMethod != null) ? builder.GetHoistedLocalScopes() : default(ImmutableArray<StateMachineHoistedLocalScope>); // Translate the imports even if we are not writing PDBs. The translation has an impact on generated metadata // and we don't want to emit different metadata depending on whether or we emit with PDB stream. // TODO (https://github.com/dotnet/roslyn/issues/2846): This will need to change for member initializers in partial class. var importScopeOpt = importChainOpt?.Translate(moduleBuilder, diagnosticsForThisMethod.DiagnosticBag); var localVariables = builder.LocalSlotManager.LocalsInOrder(); if (localVariables.Length > 0xFFFE) { diagnosticsForThisMethod.Add(ErrorCode.ERR_TooManyLocals, method.Locations.First()); } if (diagnosticsForThisMethod.HasAnyErrors()) { // we are done here. Since there were errors we should not emit anything. return null; } // We will only save the IL builders when running tests. if (moduleBuilder.SaveTestData) { moduleBuilder.SetMethodTestData(method, builder.GetSnapshot()); } var stateMachineHoistedLocalSlots = default(ImmutableArray<EncHoistedLocalInfo>); var stateMachineAwaiterSlots = default(ImmutableArray<Cci.ITypeReference>); if (optimizations == OptimizationLevel.Debug && (object)stateMachineTypeOpt != null) { Debug.Assert(method.IsAsync || method.IsIterator); GetStateMachineSlotDebugInfo(moduleBuilder, moduleBuilder.GetSynthesizedFields(stateMachineTypeOpt), variableSlotAllocatorOpt, diagnosticsForThisMethod, out stateMachineHoistedLocalSlots, out stateMachineAwaiterSlots); Debug.Assert(!diagnostics.HasAnyErrors()); } DynamicAnalysisMethodBodyData dynamicAnalysisDataOpt = null; if (emitTestCoverageData) { Debug.Assert(debugDocumentProvider != null); dynamicAnalysisDataOpt = new DynamicAnalysisMethodBodyData(dynamicAnalysisSpans); } return new MethodBody( builder.RealizedIL, builder.MaxStack, (method.PartialDefinitionPart ?? method).GetCciAdapter(), variableSlotAllocatorOpt?.MethodId ?? new DebugId(methodOrdinal, moduleBuilder.CurrentGenerationOrdinal), localVariables, builder.RealizedSequencePoints, debugDocumentProvider, builder.RealizedExceptionHandlers, builder.AreLocalsZeroed, hasStackalloc, builder.GetAllScopes(), builder.HasDynamicLocal, importScopeOpt, lambdaDebugInfo, closureDebugInfo, stateMachineTypeOpt?.Name, stateMachineHoistedLocalScopes, stateMachineHoistedLocalSlots, stateMachineAwaiterSlots, moveNextBodyDebugInfoOpt, dynamicAnalysisDataOpt); } finally { // Basic blocks contain poolable builders for IL and sequence points. Free those back // to their pools. builder.FreeBasicBlocks(); // Remember diagnostics. diagnostics.AddRange(diagnosticsForThisMethod); diagnosticsForThisMethod.Free(); } } private static void GetStateMachineSlotDebugInfo( PEModuleBuilder moduleBuilder, IEnumerable<Cci.IFieldDefinition> fieldDefs, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, out ImmutableArray<EncHoistedLocalInfo> hoistedVariableSlots, out ImmutableArray<Cci.ITypeReference> awaiterSlots) { var hoistedVariables = ArrayBuilder<EncHoistedLocalInfo>.GetInstance(); var awaiters = ArrayBuilder<Cci.ITypeReference>.GetInstance(); foreach (StateMachineFieldSymbol field in fieldDefs #if DEBUG .Select(f => ((FieldSymbolAdapter)f).AdaptedFieldSymbol) #endif ) { int index = field.SlotIndex; if (field.SlotDebugInfo.SynthesizedKind == SynthesizedLocalKind.AwaiterField) { Debug.Assert(index >= 0); while (index >= awaiters.Count) { awaiters.Add(null); } awaiters[index] = moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics.DiagnosticBag); } else if (!field.SlotDebugInfo.Id.IsNone) { Debug.Assert(index >= 0 && field.SlotDebugInfo.SynthesizedKind.IsLongLived()); while (index >= hoistedVariables.Count) { // Empty slots may be present if variables were deleted during EnC. hoistedVariables.Add(new EncHoistedLocalInfo(true)); } hoistedVariables[index] = new EncHoistedLocalInfo(field.SlotDebugInfo, moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics.DiagnosticBag)); } } // Fill in empty slots for variables deleted during EnC that are not followed by an existing variable: if (variableSlotAllocatorOpt != null) { int previousAwaiterCount = variableSlotAllocatorOpt.PreviousAwaiterSlotCount; while (awaiters.Count < previousAwaiterCount) { awaiters.Add(null); } int previousAwaiterSlotCount = variableSlotAllocatorOpt.PreviousHoistedLocalSlotCount; while (hoistedVariables.Count < previousAwaiterSlotCount) { hoistedVariables.Add(new EncHoistedLocalInfo(true)); } } hoistedVariableSlots = hoistedVariables.ToImmutableAndFree(); awaiterSlots = awaiters.ToImmutableAndFree(); } // NOTE: can return null if the method has no body. internal static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { return BindMethodBody(method, compilationState, diagnostics, nullableInitialState: null, out _, out _, out _); } // NOTE: can return null if the method has no body. private static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, NullableWalker.VariableState nullableInitialState, out ImportChain importChain, out bool originalBodyNested, out MethodBodySemanticModel.InitialState forSemanticModel) { originalBodyNested = false; importChain = null; forSemanticModel = default; BoundBlock body; if (method is SynthesizedRecordConstructor recordStructPrimaryCtor && method.ContainingType.IsRecordStruct) { body = BoundBlock.SynthesizedNoLocals(recordStructPrimaryCtor.GetSyntax()); } else if (method is SourceMemberMethodSymbol sourceMethod) { CSharpSyntaxNode syntaxNode = sourceMethod.SyntaxNode; // Static constructor can't have any this/base call if (method.MethodKind == MethodKind.StaticConstructor && syntaxNode is ConstructorDeclarationSyntax constructorSyntax && constructorSyntax.Initializer != null) { diagnostics.Add( ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, constructorSyntax.Initializer.ThisOrBaseKeyword.GetLocation(), constructorSyntax.Identifier.ValueText); } ExecutableCodeBinder bodyBinder = sourceMethod.TryGetBodyBinder(); if (sourceMethod.IsExtern || sourceMethod.IsDefaultValueTypeConstructor()) { return null; } if (bodyBinder != null) { importChain = bodyBinder.ImportChain; BoundNode methodBody = bodyBinder.BindMethodBody(syntaxNode, diagnostics); BoundNode methodBodyForSemanticModel = methodBody; NullableWalker.SnapshotManager snapshotManager = null; ImmutableDictionary<Symbol, Symbol> remappedSymbols = null; var compilation = bodyBinder.Compilation; var isSufficientLangVersion = compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); if (compilation.IsNullableAnalysisEnabledIn(method)) { methodBodyForSemanticModel = NullableWalker.AnalyzeAndRewrite( compilation, method, methodBody, bodyBinder, nullableInitialState, // if language version is insufficient, we do not want to surface nullability diagnostics, // but we should still provide nullability information through the semantic model. isSufficientLangVersion ? diagnostics.DiagnosticBag : new DiagnosticBag(), createSnapshots: true, out snapshotManager, ref remappedSymbols); } else { NullableWalker.AnalyzeIfNeeded( compilation, method, methodBody, diagnostics.DiagnosticBag, useConstructorExitWarnings: true, nullableInitialState, getFinalNullableState: false, finalNullableState: out _); } forSemanticModel = new MethodBodySemanticModel.InitialState(syntaxNode, methodBodyForSemanticModel, bodyBinder, snapshotManager, remappedSymbols); switch (methodBody.Kind) { case BoundKind.ConstructorMethodBody: var constructor = (BoundConstructorMethodBody)methodBody; body = constructor.BlockBody ?? constructor.ExpressionBody; if (constructor.Initializer != null) { ReportCtorInitializerCycles(method, constructor.Initializer.Expression, compilationState, diagnostics); if (body == null) { body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer)); } else { body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer, body)); originalBodyNested = true; } return body; } else { Debug.Assert(constructor.Locals.IsEmpty); } break; case BoundKind.NonConstructorMethodBody: var nonConstructor = (BoundNonConstructorMethodBody)methodBody; body = nonConstructor.BlockBody ?? nonConstructor.ExpressionBody; break; case BoundKind.Block: body = (BoundBlock)methodBody; break; default: throw ExceptionUtilities.UnexpectedValue(methodBody.Kind); } } else { var property = sourceMethod.AssociatedSymbol as SourcePropertySymbolBase; if ((object)property != null && property.IsAutoPropertyWithGetAccessor) { return MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMethod); } return null; } } else if (method is SynthesizedInstanceConstructor ctor) { // Synthesized instance constructors may partially synthesize // their body var node = ctor.GetNonNullSyntaxNode(); var factory = new SyntheticBoundNodeFactory(ctor, node, compilationState, diagnostics); var stmts = ArrayBuilder<BoundStatement>.GetInstance(); ctor.GenerateMethodBodyStatements(factory, stmts, diagnostics); body = BoundBlock.SynthesizedNoLocals(node, stmts.ToImmutableAndFree()); } else { // synthesized methods should return their bound bodies body = null; } if (method.IsConstructor() && method.IsImplicitlyDeclared && nullableInitialState is object) { NullableWalker.AnalyzeIfNeeded( compilationState.Compilation, method, body ?? GetSynthesizedEmptyBody(method), diagnostics.DiagnosticBag, useConstructorExitWarnings: true, nullableInitialState, getFinalNullableState: false, finalNullableState: out _); } if (method.MethodKind == MethodKind.Destructor && body != null) { return MethodBodySynthesizer.ConstructDestructorBody(method, body); } var constructorInitializer = BindImplicitConstructorInitializerIfAny(method, compilationState, diagnostics); ImmutableArray<BoundStatement> statements; if (constructorInitializer == null) { if (body != null) { return body; } statements = ImmutableArray<BoundStatement>.Empty; } else if (body == null) { statements = ImmutableArray.Create(constructorInitializer); } else { statements = ImmutableArray.Create(constructorInitializer, body); originalBodyNested = true; } return BoundBlock.SynthesizedNoLocals(method.GetNonNullSyntaxNode(), statements); } private static BoundBlock GetSynthesizedEmptyBody(Symbol symbol) { return BoundBlock.SynthesizedNoLocals(symbol.GetNonNullSyntaxNode()); } private static BoundStatement BindImplicitConstructorInitializerIfAny(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(!method.ContainingType.IsDelegateType()); // delegates have constructors but not constructor initializers if (method.MethodKind == MethodKind.Constructor && !method.IsExtern) { var compilation = method.DeclaringCompilation; var initializerInvocation = BindImplicitConstructorInitializer(method, diagnostics, compilation); if (initializerInvocation != null) { ReportCtorInitializerCycles(method, initializerInvocation, compilationState, diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. var constructorInitializer = new BoundExpressionStatement(initializerInvocation.Syntax, initializerInvocation) { WasCompilerGenerated = method.IsImplicitlyDeclared }; Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } } return null; } private static void ReportCtorInitializerCycles(MethodSymbol method, BoundExpression initializerInvocation, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var ctorCall = initializerInvocation as BoundCall; if (ctorCall != null && !ctorCall.HasAnyErrors && ctorCall.Method != method && TypeSymbol.Equals(ctorCall.Method.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything2)) { // Detect and report indirect cycles in the ctor-initializer call graph. compilationState.ReportCtorInitializerCycles(method, ctorCall.Method, ctorCall.Syntax, diagnostics); } } /// <summary> /// Bind the implicit constructor initializer of a constructor symbol. /// </summary> /// <param name="constructor">Constructor method.</param> /// <param name="diagnostics">Accumulates errors (e.g. access "this" in constructor initializer).</param> /// <param name="compilation">Used to retrieve binder.</param> /// <returns>A bound expression for the constructor initializer call.</returns> internal static BoundExpression BindImplicitConstructorInitializer( MethodSymbol constructor, BindingDiagnosticBag diagnostics, CSharpCompilation compilation) { // Note that the base type can be null if we're compiling System.Object in source. NamedTypeSymbol containingType = constructor.ContainingType; NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; SourceMemberMethodSymbol sourceConstructor = constructor as SourceMemberMethodSymbol; Debug.Assert(sourceConstructor?.SyntaxNode is RecordDeclarationSyntax || ((ConstructorDeclarationSyntax)sourceConstructor?.SyntaxNode)?.Initializer == null); // The common case is that the type inherits directly from object. // Also, we might be trying to generate a constructor for an entirely compiler-generated class such // as a closure class; in that case it is vexing to try to find a suitable binder for the non-existing // constructor syntax so that we can do unnecessary overload resolution on the non-existing initializer! // Simply take the early out: bind directly to the parameterless object ctor rather than attempting // overload resolution. if ((object)baseType != null) { if (baseType.SpecialType == SpecialType.System_Object) { return GenerateBaseParameterlessConstructorInitializer(constructor, diagnostics); } else if (baseType.IsErrorType() || baseType.IsStatic) { // If the base type is bad and there is no initializer then we can just bail. // We have no expressions we need to analyze to report errors on. return null; } } if (containingType.IsStructType() || containingType.IsEnumType()) { return null; } else if (constructor is SynthesizedRecordCopyCtor copyCtor) { return GenerateBaseCopyConstructorInitializer(copyCtor, diagnostics); } // Now, in order to do overload resolution, we're going to need a binder. There are // two possible situations: // // class D1 : B { } // class D2 : B { D2(int x) { } } // // In the first case the binder needs to be the binder associated with // the *body* of D1 because if the base class ctor is protected, we need // to be inside the body of a derived class in order for it to be in the // accessibility domain of the protected base class ctor. // // In the second case the binder could be the binder associated with // the body of D2; since the implicit call to base() will have no arguments // there is no need to look up "x". Binder outerBinder; if ((object)sourceConstructor == null) { // The constructor is implicit. We need to get the binder for the body // of the enclosing class. CSharpSyntaxNode containerNode = constructor.GetNonNullSyntaxNode(); BinderFactory binderFactory = compilation.GetBinderFactory(containerNode.SyntaxTree); if (containerNode is RecordDeclarationSyntax recordDecl) { outerBinder = binderFactory.GetInRecordBodyBinder(recordDecl); } else { SyntaxToken bodyToken = GetImplicitConstructorBodyToken(containerNode); outerBinder = binderFactory.GetBinder(containerNode, bodyToken.Position); } } else { BinderFactory binderFactory = compilation.GetBinderFactory(sourceConstructor.SyntaxTree); switch (sourceConstructor.SyntaxNode) { case ConstructorDeclarationSyntax ctorDecl: // We have a ctor in source but no explicit constructor initializer. We can't just use the binder for the // type containing the ctor because the ctor might be marked unsafe. Use the binder for the parameter list // as an approximation - the extra symbols won't matter because there are no identifiers to bind. outerBinder = binderFactory.GetBinder(ctorDecl.ParameterList); break; case RecordDeclarationSyntax recordDecl: outerBinder = binderFactory.GetInRecordBodyBinder(recordDecl); break; default: throw ExceptionUtilities.Unreachable; } } // wrap in ConstructorInitializerBinder for appropriate errors // Handle scoping for possible pattern variables declared in the initializer Binder initializerBinder = outerBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.ConstructorInitializer, constructor); return initializerBinder.BindConstructorInitializer(null, constructor, diagnostics); } private static SyntaxToken GetImplicitConstructorBodyToken(CSharpSyntaxNode containerNode) { return ((BaseTypeDeclarationSyntax)containerNode).OpenBraceToken; } internal static BoundCall GenerateBaseParameterlessConstructorInitializer(MethodSymbol constructor, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics; MethodSymbol baseConstructor = null; LookupResultKind resultKind = LookupResultKind.Viable; Location diagnosticsLocation = constructor.Locations.IsEmpty ? NoLocation.Singleton : constructor.Locations[0]; foreach (MethodSymbol ctor in baseType.InstanceConstructors) { if (ctor.ParameterCount == 0) { baseConstructor = ctor; break; } } // UNDONE: If this happens then something is deeply wrong. Should we give a better error? if ((object)baseConstructor == null) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, diagnosticsLocation, baseType, /*desired param count*/ 0); return null; } if (Binder.ReportUseSite(baseConstructor, diagnostics, diagnosticsLocation)) { return null; } // UNDONE: If this happens then something is deeply wrong. Should we give a better error? bool hasErrors = false; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, constructor.ContainingAssembly); if (!AccessCheck.IsSymbolAccessible(baseConstructor, constructor.ContainingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadAccess, diagnosticsLocation, baseConstructor); resultKind = LookupResultKind.Inaccessible; hasErrors = true; } diagnostics.Add(diagnosticsLocation, useSiteInfo); CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode(); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; return new BoundCall( syntax: syntax, receiverOpt: receiver, method: baseConstructor, arguments: ImmutableArray<BoundExpression>.Empty, argumentNamesOpt: ImmutableArray<string>.Empty, argumentRefKindsOpt: ImmutableArray<RefKind>.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: BitVector.Empty, resultKind: resultKind, type: baseConstructor.ReturnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; } private static BoundCall GenerateBaseCopyConstructorInitializer(SynthesizedRecordCopyCtor constructor, BindingDiagnosticBag diagnostics) { NamedTypeSymbol containingType = constructor.ContainingType; NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; Location diagnosticsLocation = constructor.Locations.FirstOrNone(); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, containingType.ContainingAssembly); MethodSymbol baseConstructor = SynthesizedRecordCopyCtor.FindCopyConstructor(baseType, containingType, ref useSiteInfo); if (baseConstructor is null) { diagnostics.Add(ErrorCode.ERR_NoCopyConstructorInBaseType, diagnosticsLocation, baseType); return null; } if (Binder.ReportUseSite(baseConstructor, diagnostics, diagnosticsLocation)) { return null; } diagnostics.Add(diagnosticsLocation, useSiteInfo); CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode(); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; BoundExpression argument = new BoundParameter(syntax, constructor.Parameters[0]); return new BoundCall( syntax: syntax, receiverOpt: receiver, method: baseConstructor, arguments: ImmutableArray.Create(argument), argumentNamesOpt: default, argumentRefKindsOpt: default, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default, defaultArguments: default, resultKind: LookupResultKind.Viable, type: baseConstructor.ReturnType, hasErrors: false) { WasCompilerGenerated = true }; } private static Cci.DebugSourceDocument CreateDebugDocumentForFile(string normalizedPath) { return new Cci.DebugSourceDocument(normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp); } private static bool PassesFilter(Predicate<Symbol> filterOpt, Symbol symbol) { return (filterOpt == null) || filterOpt(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. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MethodCompiler : CSharpSymbolVisitor<TypeCompilationState, object> { private readonly CSharpCompilation _compilation; private readonly bool _emittingPdb; private readonly bool _emitTestCoverageData; private readonly CancellationToken _cancellationToken; private readonly BindingDiagnosticBag _diagnostics; private readonly bool _hasDeclarationErrors; private readonly bool _emitMethodBodies; private readonly PEModuleBuilder _moduleBeingBuiltOpt; // Null if compiling for diagnostics private readonly Predicate<Symbol> _filterOpt; // If not null, limit analysis to specific symbols private readonly DebugDocumentProvider _debugDocumentProvider; private readonly SynthesizedEntryPointSymbol.AsyncForwardEntryPoint _entryPointOpt; // // MethodCompiler employs concurrency by following flattened fork/join pattern. // // For every item that we want to compile in parallel a new task is forked. // compileTaskQueue is used to track and observe all the tasks. // Once compileTaskQueue is empty, we know that there are no more tasks (and no more can be created) // and that means we are done compiling. WaitForWorkers ensures this condition. // // Note that while tasks may fork more tasks (nested types, lambdas, whatever else that may introduce more types), // we do not want any child/parent relationship between spawned tasks and their creators. // Creator has no real dependencies on the completion of its children and should finish and release any resources // as soon as it can regardless of the tasks it may have spawned. // // Stack is used so that the wait would observe the most recently added task and have // more chances to do inlined execution. private ConcurrentStack<Task> _compilerTasks; // This field tracks whether any bound method body had hasErrors set or whether any constant field had a bad value. // We track it so that we can abort emission in the event that an error occurs without a corresponding diagnostic // (e.g. if this module depends on a bad type or constant from another module). // CONSIDER: instead of storing a flag, we could track the first member symbol with an error (to improve the diagnostic). // NOTE: once the flag is set to true, it should never go back to false!!! // Do not use this as a short-circuiting for stages that might produce diagnostics. // That would make diagnostics to depend on the random order in which methods are compiled. private bool _globalHasErrors; private void SetGlobalErrorIfTrue(bool arg) { //NOTE: this is not a volatile write // for correctness we need only single threaded consistency. // Within a single task - if we have got an error it may not be safe to continue with some lowerings. // It is ok if other tasks will see the change after some delay or does not observe at all. // Such races are unavoidable and will just result in performing some work that is safe to do // but may no longer be needed. // The final Join of compiling tasks cannot happen without interlocked operations and that // will ensure that any write of the flag is globally visible. if (arg) { _globalHasErrors = true; } } // Internal for testing only. internal MethodCompiler(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool emitTestCoverageData, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate<Symbol> filterOpt, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt, CancellationToken cancellationToken) { Debug.Assert(compilation != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); Debug.Assert(diagnostics.DependenciesBag == null || diagnostics.DependenciesBag is ConcurrentSet<AssemblySymbol>); _compilation = compilation; _moduleBeingBuiltOpt = moduleBeingBuiltOpt; _emittingPdb = emittingPdb; _cancellationToken = cancellationToken; _diagnostics = diagnostics; _filterOpt = filterOpt; _entryPointOpt = entryPointOpt; _hasDeclarationErrors = hasDeclarationErrors; SetGlobalErrorIfTrue(hasDeclarationErrors); if (emittingPdb || emitTestCoverageData) { _debugDocumentProvider = (path, basePath) => moduleBeingBuiltOpt.DebugDocumentsBuilder.GetOrAddDebugDocument(path, basePath, CreateDebugDocumentForFile); } _emitTestCoverageData = emitTestCoverageData; _emitMethodBodies = emitMethodBodies; } public static void CompileMethodBodies( CSharpCompilation compilation, PEModuleBuilder moduleBeingBuiltOpt, bool emittingPdb, bool emitTestCoverageData, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, Predicate<Symbol> filterOpt, CancellationToken cancellationToken) { Debug.Assert(compilation != null); Debug.Assert(diagnostics != null); Debug.Assert(diagnostics.DiagnosticBag != null); if (compilation.PreviousSubmission != null) { // In case there is a previous submission, we should ensure // it has already created anonymous type/delegates templates // NOTE: if there are any errors, we will pick up what was created anyway compilation.PreviousSubmission.EnsureAnonymousTypeTemplates(cancellationToken); // TODO: revise to use a loop instead of a recursion } MethodSymbol entryPoint = null; if (filterOpt is null) { entryPoint = GetEntryPoint(compilation, moduleBeingBuiltOpt, hasDeclarationErrors, emitMethodBodies, diagnostics, cancellationToken); } var methodCompiler = new MethodCompiler( compilation, moduleBeingBuiltOpt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, emitMethodBodies, diagnostics, filterOpt, entryPoint as SynthesizedEntryPointSymbol.AsyncForwardEntryPoint, cancellationToken); if (compilation.Options.ConcurrentBuild) { methodCompiler._compilerTasks = new ConcurrentStack<Task>(); } // directly traverse global namespace (no point to defer this to async) methodCompiler.CompileNamespace(compilation.SourceModule.GlobalNamespace); methodCompiler.WaitForWorkers(); // compile additional and anonymous types if any if (moduleBeingBuiltOpt != null) { var additionalTypes = moduleBeingBuiltOpt.GetAdditionalTopLevelTypes(); methodCompiler.CompileSynthesizedMethods(additionalTypes, diagnostics); var embeddedTypes = moduleBeingBuiltOpt.GetEmbeddedTypes(diagnostics); methodCompiler.CompileSynthesizedMethods(embeddedTypes, diagnostics); if (emitMethodBodies) { // By this time we have processed all types reachable from module's global namespace compilation.AnonymousTypeManager.AssignTemplatesNamesAndCompile(methodCompiler, moduleBeingBuiltOpt, diagnostics); } methodCompiler.WaitForWorkers(); var privateImplClass = moduleBeingBuiltOpt.PrivateImplClass; if (privateImplClass != null) { // all threads that were adding methods must be finished now, we can freeze the class: privateImplClass.Freeze(); methodCompiler.CompileSynthesizedMethods(privateImplClass, diagnostics); } } // If we are trying to emit and there's an error without a corresponding diagnostic (e.g. because // we depend on an invalid type or constant from another module), then explicitly add a diagnostic. // This diagnostic is not very helpful to the user, but it will prevent us from emitting an invalid // module or crashing. if (moduleBeingBuiltOpt != null && (methodCompiler._globalHasErrors || moduleBeingBuiltOpt.SourceModule.HasBadAttributes) && !diagnostics.HasAnyErrors() && !hasDeclarationErrors) { var messageResourceName = methodCompiler._globalHasErrors ? nameof(CodeAnalysisResources.UnableToDetermineSpecificCauseOfFailure) : nameof(CodeAnalysisResources.ModuleHasInvalidAttributes); diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuiltOpt).Name, new LocalizableResourceString(messageResourceName, CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); } diagnostics.AddRange(compilation.AdditionalCodegenWarnings); // we can get unused field warnings only if compiling whole compilation. if (filterOpt == null) { WarnUnusedFields(compilation, diagnostics, cancellationToken); if (moduleBeingBuiltOpt != null && entryPoint != null && compilation.Options.OutputKind.IsApplication()) { moduleBeingBuiltOpt.SetPEEntryPoint(entryPoint, diagnostics.DiagnosticBag); } } } // Returns the MethodSymbol for the assembly entrypoint. If the user has a Task returning main, // this function returns the synthesized Main MethodSymbol. private static MethodSymbol GetEntryPoint(CSharpCompilation compilation, PEModuleBuilder moduleBeingBuilt, bool hasDeclarationErrors, bool emitMethodBodies, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { Debug.Assert(diagnostics.DiagnosticBag != null); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(cancellationToken); Debug.Assert(!entryPointAndDiagnostics.Diagnostics.Diagnostics.IsDefault); diagnostics.AddRange(entryPointAndDiagnostics.Diagnostics, allowMismatchInDependencyAccumulation: true); var entryPoint = entryPointAndDiagnostics.MethodSymbol; if ((object)entryPoint == null) { return null; } // entryPoint can be a SynthesizedEntryPointSymbol if a script is being compiled. SynthesizedEntryPointSymbol synthesizedEntryPoint = entryPoint as SynthesizedEntryPointSymbol; if ((object)synthesizedEntryPoint == null) { var returnType = entryPoint.ReturnType; if (returnType.IsGenericTaskType(compilation) || returnType.IsNonGenericTaskType(compilation)) { synthesizedEntryPoint = new SynthesizedEntryPointSymbol.AsyncForwardEntryPoint(compilation, entryPoint.ContainingType, entryPoint); entryPoint = synthesizedEntryPoint; if ((object)moduleBeingBuilt != null) { moduleBeingBuilt.AddSynthesizedDefinition(entryPoint.ContainingType, synthesizedEntryPoint.GetCciAdapter()); } } } if (((object)synthesizedEntryPoint != null) && (moduleBeingBuilt != null) && !hasDeclarationErrors && !diagnostics.HasAnyErrors()) { BoundStatement body = synthesizedEntryPoint.CreateBody(diagnostics); if (body.HasErrors || diagnostics.HasAnyErrors()) { return entryPoint; } var dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; VariableSlotAllocator lazyVariableSlotAllocator = null; var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); StateMachineTypeSymbol stateMachineTypeOpt = null; const int methodOrdinal = -1; var loweredBody = LowerBodyOrInitializer( synthesizedEntryPoint, methodOrdinal, body, null, new TypeCompilationState(synthesizedEntryPoint.ContainingType, compilation, moduleBeingBuilt), false, null, ref dynamicAnalysisSpans, diagnostics, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out stateMachineTypeOpt); Debug.Assert((object)lazyVariableSlotAllocator == null); Debug.Assert((object)stateMachineTypeOpt == null); Debug.Assert(dynamicAnalysisSpans.IsEmpty); Debug.Assert(lambdaDebugInfoBuilder.IsEmpty()); Debug.Assert(closureDebugInfoBuilder.IsEmpty()); lambdaDebugInfoBuilder.Free(); closureDebugInfoBuilder.Free(); if (emitMethodBodies) { var emittedBody = GenerateMethodBody( moduleBeingBuilt, synthesizedEntryPoint, methodOrdinal, loweredBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachineTypeOpt: null, variableSlotAllocatorOpt: null, diagnostics: diagnostics, debugDocumentProvider: null, importChainOpt: null, emittingPdb: false, emitTestCoverageData: false, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, entryPointOpt: null); moduleBeingBuilt.SetMethodBody(synthesizedEntryPoint, emittedBody); } } return entryPoint; } private void WaitForWorkers() { var tasks = _compilerTasks; if (tasks == null) { return; } Task curTask; while (tasks.TryPop(out curTask)) { curTask.GetAwaiter().GetResult(); } } private static void WarnUnusedFields(CSharpCompilation compilation, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { SourceAssemblySymbol assembly = (SourceAssemblySymbol)compilation.Assembly; diagnostics.AddRange(assembly.GetUnusedFieldWarnings(cancellationToken)); } public override object VisitNamespace(NamespaceSymbol symbol, TypeCompilationState arg) { if (!PassesFilter(_filterOpt, symbol)) { return null; } arg = null; // do not use compilation state of outer type. _cancellationToken.ThrowIfCancellationRequested(); if (_compilation.Options.ConcurrentBuild) { Task worker = CompileNamespaceAsAsync(symbol); _compilerTasks.Push(worker); } else { CompileNamespace(symbol); } return null; } private Task CompileNamespaceAsAsync(NamespaceSymbol symbol) { return Task.Run(UICultureUtilities.WithCurrentUICulture(() => { try { CompileNamespace(symbol); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }), _cancellationToken); } private void CompileNamespace(NamespaceSymbol symbol) { foreach (var s in symbol.GetMembersUnordered()) { s.Accept(this, null); } } public override object VisitNamedType(NamedTypeSymbol symbol, TypeCompilationState arg) { if (!PassesFilter(_filterOpt, symbol)) { return null; } arg = null; // do not use compilation state of outer type. _cancellationToken.ThrowIfCancellationRequested(); if (_compilation.Options.ConcurrentBuild) { Task worker = CompileNamedTypeAsync(symbol); _compilerTasks.Push(worker); } else { CompileNamedType(symbol); } return null; } private Task CompileNamedTypeAsync(NamedTypeSymbol symbol) { return Task.Run(UICultureUtilities.WithCurrentUICulture(() => { try { CompileNamedType(symbol); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }), _cancellationToken); } private void CompileNamedType(NamedTypeSymbol containingType) { var compilationState = new TypeCompilationState(containingType, _compilation, _moduleBeingBuiltOpt); _cancellationToken.ThrowIfCancellationRequested(); // Find the constructor of a script class. SynthesizedInstanceConstructor scriptCtor = null; SynthesizedInteractiveInitializerMethod scriptInitializer = null; SynthesizedEntryPointSymbol scriptEntryPoint = null; int scriptCtorOrdinal = -1; if (containingType.IsScriptClass) { // The field initializers of a script class could be arbitrary statements, // including blocks. Field initializers containing blocks need to // use a MethodBodySemanticModel to build up the appropriate tree of binders, and // MethodBodySemanticModel requires an "owning" method. That's why we're digging out // the constructor - it will own the field initializers. scriptCtor = containingType.GetScriptConstructor(); scriptInitializer = containingType.GetScriptInitializer(); scriptEntryPoint = containingType.GetScriptEntryPoint(); Debug.Assert((object)scriptCtor != null); Debug.Assert((object)scriptInitializer != null); } var synthesizedSubmissionFields = containingType.IsSubmissionClass ? new SynthesizedSubmissionFields(_compilation, containingType) : null; var processedStaticInitializers = new Binder.ProcessedFieldInitializers(); var processedInstanceInitializers = new Binder.ProcessedFieldInitializers(); var sourceTypeSymbol = containingType as SourceMemberContainerTypeSymbol; if ((object)sourceTypeSymbol != null) { _cancellationToken.ThrowIfCancellationRequested(); Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.StaticInitializers, _diagnostics, ref processedStaticInitializers); _cancellationToken.ThrowIfCancellationRequested(); Binder.BindFieldInitializers(_compilation, scriptInitializer, sourceTypeSymbol.InstanceInitializers, _diagnostics, ref processedInstanceInitializers); if (compilationState.Emitting) { CompileSynthesizedExplicitImplementations(sourceTypeSymbol, compilationState); } } // Indicates if a static constructor is in the member, // so we can decide to synthesize a static constructor. bool hasStaticConstructor = false; var members = containingType.GetMembers(); for (int memberOrdinal = 0; memberOrdinal < members.Length; memberOrdinal++) { var member = members[memberOrdinal]; //When a filter is supplied, limit the compilation of members passing the filter. if (!PassesFilter(_filterOpt, member)) { continue; } switch (member.Kind) { case SymbolKind.NamedType: member.Accept(this, compilationState); break; case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; if (method.IsScriptConstructor) { Debug.Assert(scriptCtorOrdinal == -1); Debug.Assert((object)scriptCtor == method); scriptCtorOrdinal = memberOrdinal; continue; } if ((object)method == scriptEntryPoint) { continue; } if (IsFieldLikeEventAccessor(method)) { continue; } if (method.IsPartialDefinition()) { method = method.PartialImplementationPart; if ((object)method == null) { continue; } } Binder.ProcessedFieldInitializers processedInitializers = (method.MethodKind == MethodKind.Constructor || method.IsScriptInitializer) ? processedInstanceInitializers : method.MethodKind == MethodKind.StaticConstructor ? processedStaticInitializers : default(Binder.ProcessedFieldInitializers); CompileMethod(method, memberOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState); // Set a flag to indicate that a static constructor is created. if (method.MethodKind == MethodKind.StaticConstructor) { hasStaticConstructor = true; } break; } case SymbolKind.Property: { var sourceProperty = member as SourcePropertySymbolBase; if ((object)sourceProperty != null && sourceProperty.IsSealed && compilationState.Emitting) { CompileSynthesizedSealedAccessors(sourceProperty, compilationState); } break; } case SymbolKind.Event: { SourceEventSymbol eventSymbol = member as SourceEventSymbol; if ((object)eventSymbol != null && eventSymbol.HasAssociatedField && !eventSymbol.IsAbstract && compilationState.Emitting) { CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: true); CompileFieldLikeEventAccessor(eventSymbol, isAddMethod: false); } break; } case SymbolKind.Field: { var fieldSymbol = (FieldSymbol)member; if (member is TupleErrorFieldSymbol) { break; } if (fieldSymbol.IsConst) { // We check specifically for constant fields with bad values because they never result // in bound nodes being inserted into method bodies (in which case, they would be covered // by the method-level check). ConstantValue constantValue = fieldSymbol.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); SetGlobalErrorIfTrue(constantValue == null || constantValue.IsBad); } if (fieldSymbol.IsFixedSizeBuffer && compilationState.Emitting) { // force the generation of implementation types for fixed-size buffers TypeSymbol discarded = fieldSymbol.FixedImplementationType(compilationState.ModuleBuilderOpt); } break; } } } Debug.Assert(containingType.IsScriptClass == (scriptCtorOrdinal >= 0)); // process additional anonymous type members if (AnonymousTypeManager.IsAnonymousTypeTemplate(containingType)) { var processedInitializers = default(Binder.ProcessedFieldInitializers); foreach (var method in AnonymousTypeManager.GetAnonymousTypeHiddenMethods(containingType)) { CompileMethod(method, -1, ref processedInitializers, synthesizedSubmissionFields, compilationState); } } // In the case there are field initializers but we haven't created an implicit static constructor (.cctor) for it, // (since we may not add .cctor implicitly created for decimals into the symbol table) // it is necessary for the compiler to generate the static constructor here if we are emitting. if (_moduleBeingBuiltOpt != null && !hasStaticConstructor && !processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty) { Debug.Assert(processedStaticInitializers.BoundInitializers.All((init) => (init.Kind == BoundKind.FieldEqualsValue) && !((BoundFieldEqualsValue)init).Field.IsMetadataConstant)); MethodSymbol method = new SynthesizedStaticConstructor(sourceTypeSymbol); if (PassesFilter(_filterOpt, method)) { CompileMethod(method, -1, ref processedStaticInitializers, synthesizedSubmissionFields, compilationState); // If this method has been successfully built, we emit it. if (_moduleBeingBuiltOpt.GetMethodBody(method) != null) { _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, method.GetCciAdapter()); } } } // If there is no explicit or implicit .cctor and no static initializers, then report // warnings for any static non-nullable fields. (If there is no .cctor, there // shouldn't be any initializers but for robustness, we check both.) if (!hasStaticConstructor && processedStaticInitializers.BoundInitializers.IsDefaultOrEmpty && _compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion() && containingType is { IsImplicitlyDeclared: false, TypeKind: TypeKind.Class or TypeKind.Struct or TypeKind.Interface }) { NullableWalker.AnalyzeIfNeeded( this._compilation, new SynthesizedStaticConstructor(containingType), GetSynthesizedEmptyBody(containingType), _diagnostics.DiagnosticBag, useConstructorExitWarnings: true, initialNullableState: null, getFinalNullableState: false, finalNullableState: out _); } // compile submission constructor last so that synthesized submission fields are collected from all script methods: if (scriptCtor != null && compilationState.Emitting) { Debug.Assert(scriptCtorOrdinal >= 0); var processedInitializers = new Binder.ProcessedFieldInitializers() { BoundInitializers = ImmutableArray<BoundInitializer>.Empty }; CompileMethod(scriptCtor, scriptCtorOrdinal, ref processedInitializers, synthesizedSubmissionFields, compilationState); if (synthesizedSubmissionFields != null) { synthesizedSubmissionFields.AddToType(containingType, compilationState.ModuleBuilderOpt); } } // Emit synthesized methods produced during lowering if any if (_moduleBeingBuiltOpt != null) { CompileSynthesizedMethods(compilationState); } compilationState.Free(); } private void CompileSynthesizedMethods(PrivateImplementationDetails privateImplClass, BindingDiagnosticBag diagnostics) { Debug.Assert(_moduleBeingBuiltOpt != null); var compilationState = new TypeCompilationState(null, _compilation, _moduleBeingBuiltOpt); foreach (Cci.IMethodDefinition definition in privateImplClass.GetMethods(new EmitContext(_moduleBeingBuiltOpt, null, diagnostics.DiagnosticBag, metadataOnly: false, includePrivateMembers: true))) { var method = (MethodSymbol)definition.GetInternalSymbol(); Debug.Assert(method.SynthesizesLoweredBoundBody); method.GenerateMethodBody(compilationState, diagnostics); } CompileSynthesizedMethods(compilationState); compilationState.Free(); } private void CompileSynthesizedMethods(ImmutableArray<NamedTypeSymbol> additionalTypes, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics.DiagnosticBag != null); foreach (var additionalType in additionalTypes) { var compilationState = new TypeCompilationState(additionalType, _compilation, _moduleBeingBuiltOpt); foreach (var method in additionalType.GetMethodsToEmit()) { method.GenerateMethodBody(compilationState, diagnostics); } if (!diagnostics.HasAnyErrors()) { CompileSynthesizedMethods(compilationState); } compilationState.Free(); } } private void CompileSynthesizedMethods(TypeCompilationState compilationState) { Debug.Assert(_moduleBeingBuiltOpt != null); Debug.Assert(compilationState.ModuleBuilderOpt == _moduleBeingBuiltOpt); var synthesizedMethods = compilationState.SynthesizedMethods; if (synthesizedMethods == null) { return; } var oldImportChain = compilationState.CurrentImportChain; try { foreach (var methodWithBody in synthesizedMethods) { var importChain = methodWithBody.ImportChain; compilationState.CurrentImportChain = importChain; // We make sure that an asynchronous mutation to the diagnostic bag does not // confuse the method body generator by making a fresh bag and then loading // any diagnostics emitted into it back into the main diagnostic bag. var diagnosticsThisMethod = BindingDiagnosticBag.GetInstance(_diagnostics); var method = methodWithBody.Method; var lambda = method as SynthesizedClosureMethod; var variableSlotAllocatorOpt = ((object)lambda != null) ? _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(lambda, lambda.TopLevelMethod, diagnosticsThisMethod.DiagnosticBag) : _moduleBeingBuiltOpt.TryCreateVariableSlotAllocator(method, method, diagnosticsThisMethod.DiagnosticBag); // Synthesized methods have no ordinal stored in custom debug information (only user-defined methods have ordinals). // In case of async lambdas, which synthesize a state machine type during the following rewrite, the containing method has already been uniquely named, // so there is no need to produce a unique method ordinal for the corresponding state machine type, whose name includes the (unique) containing method name. const int methodOrdinal = -1; MethodBody emittedBody = null; try { // Local functions can be iterators as well as be async (lambdas can only be async), so we need to lower both iterators and async IteratorStateMachine iteratorStateMachine; BoundStatement loweredBody = IteratorRewriter.Rewrite(methodWithBody.Body, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out iteratorStateMachine); StateMachineTypeSymbol stateMachine = iteratorStateMachine; if (!loweredBody.HasErrors) { AsyncStateMachine asyncStateMachine; loweredBody = AsyncRewriter.Rewrite(loweredBody, method, methodOrdinal, variableSlotAllocatorOpt, compilationState, diagnosticsThisMethod, out asyncStateMachine); Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null); stateMachine = stateMachine ?? asyncStateMachine; } if (_emitMethodBodies && !diagnosticsThisMethod.HasAnyErrors() && !_globalHasErrors) { emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, method, methodOrdinal, loweredBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachine, variableSlotAllocatorOpt, diagnosticsThisMethod, _debugDocumentProvider, method.GenerateDebugInfo ? importChain : null, emittingPdb: _emittingPdb, emitTestCoverageData: _emitTestCoverageData, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, _entryPointOpt); } } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(_diagnostics); } _diagnostics.AddRange(diagnosticsThisMethod); diagnosticsThisMethod.Free(); if (_emitMethodBodies) { // error while generating IL if (emittedBody == null) { break; } _moduleBeingBuiltOpt.SetMethodBody(method, emittedBody); } else { Debug.Assert(emittedBody is null); } } } finally { compilationState.CurrentImportChain = oldImportChain; } } private static bool IsFieldLikeEventAccessor(MethodSymbol method) { Symbol associatedPropertyOrEvent = method.AssociatedSymbol; return (object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event && ((EventSymbol)associatedPropertyOrEvent).HasAssociatedField; } /// <summary> /// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a /// base type from another assembly) it is necessary for the compiler to generate explicit implementations for /// some interface methods. They don't go in the symbol table, but if we are emitting, then we should /// generate code for them. /// </summary> private void CompileSynthesizedExplicitImplementations(SourceMemberContainerTypeSymbol sourceTypeSymbol, TypeCompilationState compilationState) { // we are not generating any observable diagnostics here so it is ok to short-circuit on global errors. if (!_globalHasErrors) { var discardedDiagnostics = BindingDiagnosticBag.GetInstance(_diagnostics); foreach (var synthesizedExplicitImpl in sourceTypeSymbol.GetSynthesizedExplicitImplementations(_cancellationToken).ForwardingMethods) { Debug.Assert(synthesizedExplicitImpl.SynthesizesLoweredBoundBody); synthesizedExplicitImpl.GenerateMethodBody(compilationState, discardedDiagnostics); Debug.Assert(!discardedDiagnostics.HasAnyErrors()); discardedDiagnostics.DiagnosticBag.Clear(); _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceTypeSymbol, synthesizedExplicitImpl.GetCciAdapter()); } _diagnostics.AddRangeAndFree(discardedDiagnostics); } } private void CompileSynthesizedSealedAccessors(SourcePropertySymbolBase sourceProperty, TypeCompilationState compilationState) { SynthesizedSealedPropertyAccessor synthesizedAccessor = sourceProperty.SynthesizedSealedAccessorOpt; // we are not generating any observable diagnostics here so it is ok to short-circuit on global errors. if ((object)synthesizedAccessor != null && !_globalHasErrors) { Debug.Assert(synthesizedAccessor.SynthesizesLoweredBoundBody); var discardedDiagnostics = BindingDiagnosticBag.GetInstance(_diagnostics); synthesizedAccessor.GenerateMethodBody(compilationState, discardedDiagnostics); Debug.Assert(!discardedDiagnostics.HasAnyErrors()); _diagnostics.AddDependencies(discardedDiagnostics); discardedDiagnostics.Free(); _moduleBeingBuiltOpt.AddSynthesizedDefinition(sourceProperty.ContainingType, synthesizedAccessor.GetCciAdapter()); } } private void CompileFieldLikeEventAccessor(SourceEventSymbol eventSymbol, bool isAddMethod) { MethodSymbol accessor = isAddMethod ? eventSymbol.AddMethod : eventSymbol.RemoveMethod; var diagnosticsThisMethod = BindingDiagnosticBag.GetInstance(_diagnostics); try { BoundBlock boundBody = MethodBodySynthesizer.ConstructFieldLikeEventAccessorBody(eventSymbol, isAddMethod, _compilation, diagnosticsThisMethod); var hasErrors = diagnosticsThisMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); // we cannot rely on GlobalHasErrors since that can be changed concurrently by other methods compiling // we however do not want to continue with generating method body if we have errors in this particular method - generating may crash // or if had declaration errors - we will fail anyways, but if some types are bad enough, generating may produce duplicate errors about that. if (!hasErrors && !_hasDeclarationErrors && _emitMethodBodies) { const int accessorOrdinal = -1; MethodBody emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, accessor, accessorOrdinal, boundBody, ImmutableArray<LambdaDebugInfo>.Empty, ImmutableArray<ClosureDebugInfo>.Empty, stateMachineTypeOpt: null, variableSlotAllocatorOpt: null, diagnostics: diagnosticsThisMethod, debugDocumentProvider: _debugDocumentProvider, importChainOpt: null, emittingPdb: false, emitTestCoverageData: _emitTestCoverageData, dynamicAnalysisSpans: ImmutableArray<SourceSpan>.Empty, entryPointOpt: null); _moduleBeingBuiltOpt.SetMethodBody(accessor, emittedBody); // Definition is already in the symbol table, so don't call moduleBeingBuilt.AddCompilerGeneratedDefinition } } finally { _diagnostics.AddRange(diagnosticsThisMethod); diagnosticsThisMethod.Free(); } } public override object VisitMethod(MethodSymbol symbol, TypeCompilationState arg) { throw ExceptionUtilities.Unreachable; } public override object VisitProperty(PropertySymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } public override object VisitEvent(EventSymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } public override object VisitField(FieldSymbol symbol, TypeCompilationState argument) { throw ExceptionUtilities.Unreachable; } private void CompileMethod( MethodSymbol methodSymbol, int methodOrdinal, ref Binder.ProcessedFieldInitializers processedInitializers, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState) { _cancellationToken.ThrowIfCancellationRequested(); SourceMemberMethodSymbol sourceMethod = methodSymbol as SourceMemberMethodSymbol; if (methodSymbol.IsAbstract || methodSymbol.ContainingType?.IsDelegateType() == true) { if ((object)sourceMethod != null) { bool diagsWritten; sourceMethod.SetDiagnostics(ImmutableArray<Diagnostic>.Empty, out diagsWritten); if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null) { _compilation.SymbolDeclaredEvent(methodSymbol); } } return; } // get cached diagnostics if not building and we have 'em if (_moduleBeingBuiltOpt == null && (object)sourceMethod != null) { var cachedDiagnostics = sourceMethod.Diagnostics; if (!cachedDiagnostics.IsDefault) { _diagnostics.AddRange(cachedDiagnostics); return; } } ImportChain oldImportChain = compilationState.CurrentImportChain; // In order to avoid generating code for methods with errors, we create a diagnostic bag just for this method. var diagsForCurrentMethod = BindingDiagnosticBag.GetInstance(_diagnostics); try { // if synthesized method returns its body in lowered form if (methodSymbol.SynthesizesLoweredBoundBody) { if (_moduleBeingBuiltOpt != null) { methodSymbol.GenerateMethodBody(compilationState, diagsForCurrentMethod); _diagnostics.AddRange(diagsForCurrentMethod); } return; } // no need to emit the default ctor, we are not emitting those if (methodSymbol.IsDefaultValueTypeConstructor()) { return; } bool includeNonEmptyInitializersInBody = false; BoundBlock body; bool originalBodyNested = false; // initializers that have been analyzed but not yet lowered. BoundStatementList analyzedInitializers = null; MethodBodySemanticModel.InitialState forSemanticModel = default; ImportChain importChain = null; var hasTrailingExpression = false; if (methodSymbol.IsScriptConstructor) { Debug.Assert(methodSymbol.IsImplicitlyDeclared); body = new BoundBlock(methodSymbol.GetNonNullSyntaxNode(), ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty) { WasCompilerGenerated = true }; } else if (methodSymbol.IsScriptInitializer) { Debug.Assert(methodSymbol.IsImplicitlyDeclared); // rewrite top-level statements and script variable declarations to a list of statements and assignments, respectively: var initializerStatements = InitializerRewriter.RewriteScriptInitializer(processedInitializers.BoundInitializers, (SynthesizedInteractiveInitializerMethod)methodSymbol, out hasTrailingExpression); // the lowered script initializers should not be treated as initializers anymore but as a method body: body = BoundBlock.SynthesizedNoLocals(initializerStatements.Syntax, initializerStatements.Statements); NullableWalker.AnalyzeIfNeeded( _compilation, methodSymbol, initializerStatements, diagsForCurrentMethod.DiagnosticBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out processedInitializers.AfterInitializersState); var unusedDiagnostics = DiagnosticBag.GetInstance(); DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, initializerStatements, unusedDiagnostics, requireOutParamsAssigned: false); DiagnosticsPass.IssueDiagnostics(_compilation, initializerStatements, BindingDiagnosticBag.Discarded, methodSymbol); unusedDiagnostics.Free(); } else { var includeInitializersInBody = methodSymbol.IncludeFieldInitializersInBody(); // Do not emit initializers if we are invoking another constructor of this class. includeNonEmptyInitializersInBody = includeInitializersInBody && !processedInitializers.BoundInitializers.IsDefaultOrEmpty; if (includeNonEmptyInitializersInBody && processedInitializers.LoweredInitializers == null) { analyzedInitializers = InitializerRewriter.RewriteConstructor(processedInitializers.BoundInitializers, methodSymbol); processedInitializers.HasErrors = processedInitializers.HasErrors || analyzedInitializers.HasAnyErrors; } if (includeInitializersInBody && processedInitializers.AfterInitializersState is null) { NullableWalker.AnalyzeIfNeeded( _compilation, methodSymbol, // we analyze to produce an AfterInitializersState even if there are no initializers // because it conveniently allows us to capture all the 'default' states for applicable members analyzedInitializers ?? GetSynthesizedEmptyBody(methodSymbol), diagsForCurrentMethod.DiagnosticBag, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out processedInitializers.AfterInitializersState); } body = BindMethodBody(methodSymbol, compilationState, diagsForCurrentMethod, processedInitializers.AfterInitializersState, out importChain, out originalBodyNested, out forSemanticModel); if (diagsForCurrentMethod.HasAnyErrors() && body != null) { body = (BoundBlock)body.WithHasErrors(); } // lower initializers just once. the lowered tree will be reused when emitting all constructors // with field initializers. Once lowered, these initializers will be stashed in processedInitializers.LoweredInitializers // (see later in this method). Don't bother lowering _now_ if this particular ctor won't have the initializers // appended to its body. if (includeNonEmptyInitializersInBody && processedInitializers.LoweredInitializers == null) { if (body != null && ((methodSymbol.ContainingType.IsStructType() && !methodSymbol.IsImplicitConstructor) || methodSymbol is SynthesizedRecordConstructor || _emitTestCoverageData)) { if (_emitTestCoverageData && methodSymbol.IsImplicitConstructor) { // Flow analysis over the initializers is necessary in order to find assignments to fields. // Bodies of implicit constructors do not get flow analysis later, so the initializers // are analyzed here. DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod.DiagnosticBag, requireOutParamsAssigned: false); } // In order to get correct diagnostics, we need to analyze initializers and the body together. body = body.Update(body.Locals, body.LocalFunctions, body.Statements.Insert(0, analyzedInitializers)); includeNonEmptyInitializersInBody = false; analyzedInitializers = null; } else { // These analyses check for diagnostics in lambdas. // Control flow analysis and implicit return insertion are unnecessary. DefiniteAssignmentPass.Analyze(_compilation, methodSymbol, analyzedInitializers, diagsForCurrentMethod.DiagnosticBag, requireOutParamsAssigned: false); DiagnosticsPass.IssueDiagnostics(_compilation, analyzedInitializers, diagsForCurrentMethod, methodSymbol); } } } #if DEBUG // If the method is a synthesized static or instance constructor, then debugImports will be null and we will use the value // from the first field initializer. if ((methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) && methodSymbol.IsImplicitlyDeclared && body == null) { // There was no body to bind, so we didn't get anything from BindMethodBody. Debug.Assert(importChain == null); } // Either there were no field initializers or we grabbed debug imports from the first one. Debug.Assert(processedInitializers.BoundInitializers.IsDefaultOrEmpty || processedInitializers.FirstImportChain != null); #endif importChain = importChain ?? processedInitializers.FirstImportChain; // Associate these debug imports with all methods generated from this one. compilationState.CurrentImportChain = importChain; if (body != null) { DiagnosticsPass.IssueDiagnostics(_compilation, body, diagsForCurrentMethod, methodSymbol); } BoundBlock flowAnalyzedBody = null; if (body != null) { flowAnalyzedBody = FlowAnalysisPass.Rewrite(methodSymbol, body, diagsForCurrentMethod.DiagnosticBag, hasTrailingExpression: hasTrailingExpression, originalBodyNested: originalBodyNested); } bool hasErrors = _hasDeclarationErrors || diagsForCurrentMethod.HasAnyErrors() || processedInitializers.HasErrors; // Record whether or not the bound tree for the lowered method body (including any initializers) contained any // errors (note: errors, not diagnostics). SetGlobalErrorIfTrue(hasErrors); bool diagsWritten = false; var actualDiagnostics = diagsForCurrentMethod.ToReadOnly(); if (sourceMethod != null) { actualDiagnostics = new ImmutableBindingDiagnostic<AssemblySymbol>(sourceMethod.SetDiagnostics(actualDiagnostics.Diagnostics, out diagsWritten), actualDiagnostics.Dependencies); } if (diagsWritten && !methodSymbol.IsImplicitlyDeclared && _compilation.EventQueue != null) { // If compilation has a caching semantic model provider, then cache the already-computed bound tree // onto the semantic model and store it on the event. SyntaxTreeSemanticModel semanticModelWithCachedBoundNodes = null; if (body != null && forSemanticModel.Syntax is { } semanticModelSyntax && _compilation.SemanticModelProvider is CachingSemanticModelProvider cachingSemanticModelProvider) { var syntax = body.Syntax; semanticModelWithCachedBoundNodes = (SyntaxTreeSemanticModel)cachingSemanticModelProvider.GetSemanticModel(syntax.SyntaxTree, _compilation); semanticModelWithCachedBoundNodes.GetOrAddModel(semanticModelSyntax, (rootSyntax) => { Debug.Assert(rootSyntax == forSemanticModel.Syntax); return MethodBodySemanticModel.Create(semanticModelWithCachedBoundNodes, methodSymbol, forSemanticModel); }); } _compilation.EventQueue.TryEnqueue(new SymbolDeclaredCompilationEvent(_compilation, methodSymbol.GetPublicSymbol(), semanticModelWithCachedBoundNodes)); } // Don't lower if we're not emitting or if there were errors. // Methods that had binding errors are considered too broken to be lowered reliably. if (_moduleBeingBuiltOpt == null || hasErrors) { _diagnostics.AddRange(actualDiagnostics); return; } // ############################ // LOWERING AND EMIT // Any errors generated below here are considered Emit diagnostics // and will not be reported to callers Compilation.GetDiagnostics() ImmutableArray<SourceSpan> dynamicAnalysisSpans = ImmutableArray<SourceSpan>.Empty; bool hasBody = flowAnalyzedBody != null; VariableSlotAllocator lazyVariableSlotAllocator = null; StateMachineTypeSymbol stateMachineTypeOpt = null; var lambdaDebugInfoBuilder = ArrayBuilder<LambdaDebugInfo>.GetInstance(); var closureDebugInfoBuilder = ArrayBuilder<ClosureDebugInfo>.GetInstance(); BoundStatement loweredBodyOpt = null; try { if (hasBody) { loweredBodyOpt = LowerBodyOrInitializer( methodSymbol, methodOrdinal, flowAnalyzedBody, previousSubmissionFields, compilationState, _emitTestCoverageData, _debugDocumentProvider, ref dynamicAnalysisSpans, diagsForCurrentMethod, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out stateMachineTypeOpt); Debug.Assert(loweredBodyOpt != null); } else { loweredBodyOpt = null; } hasErrors = hasErrors || (hasBody && loweredBodyOpt.HasErrors) || diagsForCurrentMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); // don't emit if the resulting method would contain initializers with errors if (!hasErrors && (hasBody || includeNonEmptyInitializersInBody)) { Debug.Assert(!(methodSymbol.IsImplicitInstanceConstructor && methodSymbol.ParameterCount == 0) || !methodSymbol.ContainingType.IsStructType()); // Fields must be initialized before constructor initializer (which is the first statement of the analyzed body, if specified), // so that the initialization occurs before any method overridden by the declaring class can be invoked from the base constructor // and access the fields. ImmutableArray<BoundStatement> boundStatements; if (methodSymbol.IsScriptConstructor) { boundStatements = MethodBodySynthesizer.ConstructScriptConstructorBody(loweredBodyOpt, methodSymbol, previousSubmissionFields, _compilation); } else { boundStatements = ImmutableArray<BoundStatement>.Empty; if (analyzedInitializers != null) { // For dynamic analysis, field initializers are instrumented as part of constructors, // and so are never instrumented here. Debug.Assert(!_emitTestCoverageData); StateMachineTypeSymbol initializerStateMachineTypeOpt; BoundStatement lowered = LowerBodyOrInitializer( methodSymbol, methodOrdinal, analyzedInitializers, previousSubmissionFields, compilationState, _emitTestCoverageData, _debugDocumentProvider, ref dynamicAnalysisSpans, diagsForCurrentMethod, ref lazyVariableSlotAllocator, lambdaDebugInfoBuilder, closureDebugInfoBuilder, out initializerStateMachineTypeOpt); processedInitializers.LoweredInitializers = lowered; // initializers can't produce state machines Debug.Assert((object)initializerStateMachineTypeOpt == null); Debug.Assert(!hasErrors); hasErrors = lowered.HasAnyErrors || diagsForCurrentMethod.HasAnyErrors(); SetGlobalErrorIfTrue(hasErrors); if (hasErrors) { _diagnostics.AddRange(diagsForCurrentMethod); return; } // Only do the cast if we haven't returned with some error diagnostics. // Otherwise, `lowered` might have been a BoundBadStatement. processedInitializers.LoweredInitializers = (BoundStatementList)lowered; } // initializers for global code have already been included in the body if (includeNonEmptyInitializersInBody) { if (processedInitializers.LoweredInitializers.Kind == BoundKind.StatementList) { BoundStatementList lowered = (BoundStatementList)processedInitializers.LoweredInitializers; boundStatements = boundStatements.Concat(lowered.Statements); } else { boundStatements = boundStatements.Add(processedInitializers.LoweredInitializers); } } if (hasBody) { boundStatements = boundStatements.Concat(ImmutableArray.Create(loweredBodyOpt)); } } if (_emitMethodBodies && (!(methodSymbol is SynthesizedStaticConstructor cctor) || cctor.ShouldEmit(processedInitializers.BoundInitializers))) { CSharpSyntaxNode syntax = methodSymbol.GetNonNullSyntaxNode(); var boundBody = BoundStatementList.Synthesized(syntax, boundStatements); var emittedBody = GenerateMethodBody( _moduleBeingBuiltOpt, methodSymbol, methodOrdinal, boundBody, lambdaDebugInfoBuilder.ToImmutable(), closureDebugInfoBuilder.ToImmutable(), stateMachineTypeOpt, lazyVariableSlotAllocator, diagsForCurrentMethod, _debugDocumentProvider, importChain, _emittingPdb, _emitTestCoverageData, dynamicAnalysisSpans, entryPointOpt: null); _moduleBeingBuiltOpt.SetMethodBody(methodSymbol.PartialDefinitionPart ?? methodSymbol, emittedBody); } } _diagnostics.AddRange(diagsForCurrentMethod); } finally { lambdaDebugInfoBuilder.Free(); closureDebugInfoBuilder.Free(); } } finally { diagsForCurrentMethod.Free(); compilationState.CurrentImportChain = oldImportChain; } } // internal for testing internal static BoundStatement LowerBodyOrInitializer( MethodSymbol method, int methodOrdinal, BoundStatement body, SynthesizedSubmissionFields previousSubmissionFields, TypeCompilationState compilationState, bool instrumentForDynamicAnalysis, DebugDocumentProvider debugDocumentProvider, ref ImmutableArray<SourceSpan> dynamicAnalysisSpans, BindingDiagnosticBag diagnostics, ref VariableSlotAllocator lazyVariableSlotAllocator, ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder, ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder, out StateMachineTypeSymbol stateMachineTypeOpt) { Debug.Assert(compilationState.ModuleBuilderOpt != null); stateMachineTypeOpt = null; if (body.HasErrors) { return body; } try { var loweredBody = LocalRewriter.Rewrite( method.DeclaringCompilation, method, methodOrdinal, method.ContainingType, body, compilationState, previousSubmissionFields: previousSubmissionFields, allowOmissionOfConditionalCalls: true, instrumentForDynamicAnalysis: instrumentForDynamicAnalysis, debugDocumentProvider: debugDocumentProvider, dynamicAnalysisSpans: ref dynamicAnalysisSpans, diagnostics: diagnostics, sawLambdas: out bool sawLambdas, sawLocalFunctions: out bool sawLocalFunctions, sawAwaitInExceptionHandler: out bool sawAwaitInExceptionHandler); if (loweredBody.HasErrors) { return loweredBody; } if (sawAwaitInExceptionHandler) { // If we have awaits in handlers, we need to // replace handlers with synthetic ones which can be consumed by async rewriter. // The reason why this rewrite happens before the lambda rewrite // is that we may need access to exception locals and it would be fairly hard to do // if these locals are captured into closures (possibly nested ones). loweredBody = AsyncExceptionHandlerRewriter.Rewrite( method, method.ContainingType, loweredBody, compilationState, diagnostics); } if (loweredBody.HasErrors) { return loweredBody; } if (lazyVariableSlotAllocator == null) { lazyVariableSlotAllocator = compilationState.ModuleBuilderOpt.TryCreateVariableSlotAllocator(method, method, diagnostics.DiagnosticBag); } BoundStatement bodyWithoutLambdas = loweredBody; if (sawLambdas || sawLocalFunctions) { bodyWithoutLambdas = ClosureConversion.Rewrite( loweredBody, method.ContainingType, method.ThisParameter, method, methodOrdinal, null, lambdaDebugInfoBuilder, closureDebugInfoBuilder, lazyVariableSlotAllocator, compilationState, diagnostics, assignLocals: null); } if (bodyWithoutLambdas.HasErrors) { return bodyWithoutLambdas; } BoundStatement bodyWithoutIterators = IteratorRewriter.Rewrite(bodyWithoutLambdas, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics, out IteratorStateMachine iteratorStateMachine); if (bodyWithoutIterators.HasErrors) { return bodyWithoutIterators; } BoundStatement bodyWithoutAsync = AsyncRewriter.Rewrite(bodyWithoutIterators, method, methodOrdinal, lazyVariableSlotAllocator, compilationState, diagnostics, out AsyncStateMachine asyncStateMachine); Debug.Assert((object)iteratorStateMachine == null || (object)asyncStateMachine == null); stateMachineTypeOpt = (StateMachineTypeSymbol)iteratorStateMachine ?? asyncStateMachine; return bodyWithoutAsync; } catch (BoundTreeVisitor.CancelledByStackGuardException ex) { ex.AddAnError(diagnostics); return new BoundBadStatement(body.Syntax, ImmutableArray.Create<BoundNode>(body), hasErrors: true); } } /// <summary> /// entryPointOpt is only considered for synthesized methods (to recognize the synthesized MoveNext method for async Main) /// </summary> private static MethodBody GenerateMethodBody( PEModuleBuilder moduleBuilder, MethodSymbol method, int methodOrdinal, BoundStatement block, ImmutableArray<LambdaDebugInfo> lambdaDebugInfo, ImmutableArray<ClosureDebugInfo> closureDebugInfo, StateMachineTypeSymbol stateMachineTypeOpt, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, DebugDocumentProvider debugDocumentProvider, ImportChain importChainOpt, bool emittingPdb, bool emitTestCoverageData, ImmutableArray<SourceSpan> dynamicAnalysisSpans, SynthesizedEntryPointSymbol.AsyncForwardEntryPoint entryPointOpt) { // Note: don't call diagnostics.HasAnyErrors() in release; could be expensive if compilation has many warnings. Debug.Assert(!diagnostics.HasAnyErrors(), "Running code generator when errors exist might be dangerous; code generator not expecting errors"); var compilation = moduleBuilder.Compilation; var localSlotManager = new LocalSlotManager(variableSlotAllocatorOpt); var optimizations = compilation.Options.OptimizationLevel; ILBuilder builder = new ILBuilder(moduleBuilder, localSlotManager, optimizations, method.AreLocalsZeroed); bool hasStackalloc; var diagnosticsForThisMethod = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); try { StateMachineMoveNextBodyDebugInfo moveNextBodyDebugInfoOpt = null; var codeGen = new CodeGen.CodeGenerator(method, block, builder, moduleBuilder, diagnosticsForThisMethod.DiagnosticBag, optimizations, emittingPdb); if (diagnosticsForThisMethod.HasAnyErrors()) { // we are done here. Since there were errors we should not emit anything. return null; } bool isAsyncStateMachine; MethodSymbol kickoffMethod; if (method is SynthesizedStateMachineMethod stateMachineMethod && method.Name == WellKnownMemberNames.MoveNextMethodName) { kickoffMethod = stateMachineMethod.StateMachineType.KickoffMethod; Debug.Assert(kickoffMethod != null); isAsyncStateMachine = kickoffMethod.IsAsync; // Async void method may be partial. Debug info needs to be associated with the emitted definition, // but the kickoff method is the method implementation (the part with body). kickoffMethod = kickoffMethod.PartialDefinitionPart ?? kickoffMethod; } else { kickoffMethod = null; isAsyncStateMachine = false; } if (isAsyncStateMachine) { codeGen.Generate(out int asyncCatchHandlerOffset, out var asyncYieldPoints, out var asyncResumePoints, out hasStackalloc); // The exception handler IL offset is used by the debugger to treat exceptions caught by the marked catch block as "user unhandled". // This is important for async void because async void exceptions generally result in the process being terminated, // but without anything useful on the call stack. Async Task methods on the other hand return exceptions as the result of the Task. // So it is undesirable to consider these exceptions "user unhandled" since there may well be user code that is awaiting the task. // This is a heuristic since it's possible that there is no user code awaiting the task. // We do the same for async Main methods, since it is unlikely that user code will be awaiting the Task: // AsyncForwardEntryPoint <Main> -> kick-off method Main -> MoveNext. bool isAsyncMainMoveNext = entryPointOpt?.UserMain.Equals(kickoffMethod) == true; moveNextBodyDebugInfoOpt = new AsyncMoveNextBodyDebugInfo( kickoffMethod.GetCciAdapter(), catchHandlerOffset: (kickoffMethod.ReturnsVoid || isAsyncMainMoveNext) ? asyncCatchHandlerOffset : -1, asyncYieldPoints, asyncResumePoints); } else { codeGen.Generate(out hasStackalloc); if ((object)kickoffMethod != null) { moveNextBodyDebugInfoOpt = new IteratorMoveNextBodyDebugInfo(kickoffMethod.GetCciAdapter()); } } // Compiler-generated MoveNext methods have hoisted local scopes. // These are built by call to CodeGen.Generate. var stateMachineHoistedLocalScopes = ((object)kickoffMethod != null) ? builder.GetHoistedLocalScopes() : default(ImmutableArray<StateMachineHoistedLocalScope>); // Translate the imports even if we are not writing PDBs. The translation has an impact on generated metadata // and we don't want to emit different metadata depending on whether or we emit with PDB stream. // TODO (https://github.com/dotnet/roslyn/issues/2846): This will need to change for member initializers in partial class. var importScopeOpt = importChainOpt?.Translate(moduleBuilder, diagnosticsForThisMethod.DiagnosticBag); var localVariables = builder.LocalSlotManager.LocalsInOrder(); if (localVariables.Length > 0xFFFE) { diagnosticsForThisMethod.Add(ErrorCode.ERR_TooManyLocals, method.Locations.First()); } if (diagnosticsForThisMethod.HasAnyErrors()) { // we are done here. Since there were errors we should not emit anything. return null; } // We will only save the IL builders when running tests. if (moduleBuilder.SaveTestData) { moduleBuilder.SetMethodTestData(method, builder.GetSnapshot()); } var stateMachineHoistedLocalSlots = default(ImmutableArray<EncHoistedLocalInfo>); var stateMachineAwaiterSlots = default(ImmutableArray<Cci.ITypeReference>); if (optimizations == OptimizationLevel.Debug && (object)stateMachineTypeOpt != null) { Debug.Assert(method.IsAsync || method.IsIterator); GetStateMachineSlotDebugInfo(moduleBuilder, moduleBuilder.GetSynthesizedFields(stateMachineTypeOpt), variableSlotAllocatorOpt, diagnosticsForThisMethod, out stateMachineHoistedLocalSlots, out stateMachineAwaiterSlots); Debug.Assert(!diagnostics.HasAnyErrors()); } DynamicAnalysisMethodBodyData dynamicAnalysisDataOpt = null; if (emitTestCoverageData) { Debug.Assert(debugDocumentProvider != null); dynamicAnalysisDataOpt = new DynamicAnalysisMethodBodyData(dynamicAnalysisSpans); } return new MethodBody( builder.RealizedIL, builder.MaxStack, (method.PartialDefinitionPart ?? method).GetCciAdapter(), variableSlotAllocatorOpt?.MethodId ?? new DebugId(methodOrdinal, moduleBuilder.CurrentGenerationOrdinal), localVariables, builder.RealizedSequencePoints, debugDocumentProvider, builder.RealizedExceptionHandlers, builder.AreLocalsZeroed, hasStackalloc, builder.GetAllScopes(), builder.HasDynamicLocal, importScopeOpt, lambdaDebugInfo, closureDebugInfo, stateMachineTypeOpt?.Name, stateMachineHoistedLocalScopes, stateMachineHoistedLocalSlots, stateMachineAwaiterSlots, moveNextBodyDebugInfoOpt, dynamicAnalysisDataOpt); } finally { // Basic blocks contain poolable builders for IL and sequence points. Free those back // to their pools. builder.FreeBasicBlocks(); // Remember diagnostics. diagnostics.AddRange(diagnosticsForThisMethod); diagnosticsForThisMethod.Free(); } } private static void GetStateMachineSlotDebugInfo( PEModuleBuilder moduleBuilder, IEnumerable<Cci.IFieldDefinition> fieldDefs, VariableSlotAllocator variableSlotAllocatorOpt, BindingDiagnosticBag diagnostics, out ImmutableArray<EncHoistedLocalInfo> hoistedVariableSlots, out ImmutableArray<Cci.ITypeReference> awaiterSlots) { var hoistedVariables = ArrayBuilder<EncHoistedLocalInfo>.GetInstance(); var awaiters = ArrayBuilder<Cci.ITypeReference>.GetInstance(); foreach (StateMachineFieldSymbol field in fieldDefs #if DEBUG .Select(f => ((FieldSymbolAdapter)f).AdaptedFieldSymbol) #endif ) { int index = field.SlotIndex; if (field.SlotDebugInfo.SynthesizedKind == SynthesizedLocalKind.AwaiterField) { Debug.Assert(index >= 0); while (index >= awaiters.Count) { awaiters.Add(null); } awaiters[index] = moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics.DiagnosticBag); } else if (!field.SlotDebugInfo.Id.IsNone) { Debug.Assert(index >= 0 && field.SlotDebugInfo.SynthesizedKind.IsLongLived()); while (index >= hoistedVariables.Count) { // Empty slots may be present if variables were deleted during EnC. hoistedVariables.Add(new EncHoistedLocalInfo(true)); } hoistedVariables[index] = new EncHoistedLocalInfo(field.SlotDebugInfo, moduleBuilder.EncTranslateLocalVariableType(field.Type, diagnostics.DiagnosticBag)); } } // Fill in empty slots for variables deleted during EnC that are not followed by an existing variable: if (variableSlotAllocatorOpt != null) { int previousAwaiterCount = variableSlotAllocatorOpt.PreviousAwaiterSlotCount; while (awaiters.Count < previousAwaiterCount) { awaiters.Add(null); } int previousAwaiterSlotCount = variableSlotAllocatorOpt.PreviousHoistedLocalSlotCount; while (hoistedVariables.Count < previousAwaiterSlotCount) { hoistedVariables.Add(new EncHoistedLocalInfo(true)); } } hoistedVariableSlots = hoistedVariables.ToImmutableAndFree(); awaiterSlots = awaiters.ToImmutableAndFree(); } // NOTE: can return null if the method has no body. internal static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { return BindMethodBody(method, compilationState, diagnostics, nullableInitialState: null, out _, out _, out _); } // NOTE: can return null if the method has no body. private static BoundBlock BindMethodBody(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics, NullableWalker.VariableState nullableInitialState, out ImportChain importChain, out bool originalBodyNested, out MethodBodySemanticModel.InitialState forSemanticModel) { originalBodyNested = false; importChain = null; forSemanticModel = default; BoundBlock body; if (method is SynthesizedRecordConstructor recordStructPrimaryCtor && method.ContainingType.IsRecordStruct) { body = BoundBlock.SynthesizedNoLocals(recordStructPrimaryCtor.GetSyntax()); } else if (method is SourceMemberMethodSymbol sourceMethod) { CSharpSyntaxNode syntaxNode = sourceMethod.SyntaxNode; // Static constructor can't have any this/base call if (method.MethodKind == MethodKind.StaticConstructor && syntaxNode is ConstructorDeclarationSyntax constructorSyntax && constructorSyntax.Initializer != null) { diagnostics.Add( ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, constructorSyntax.Initializer.ThisOrBaseKeyword.GetLocation(), constructorSyntax.Identifier.ValueText); } ExecutableCodeBinder bodyBinder = sourceMethod.TryGetBodyBinder(); if (sourceMethod.IsExtern || sourceMethod.IsDefaultValueTypeConstructor()) { return null; } if (bodyBinder != null) { importChain = bodyBinder.ImportChain; BoundNode methodBody = bodyBinder.BindMethodBody(syntaxNode, diagnostics); BoundNode methodBodyForSemanticModel = methodBody; NullableWalker.SnapshotManager snapshotManager = null; ImmutableDictionary<Symbol, Symbol> remappedSymbols = null; var compilation = bodyBinder.Compilation; var isSufficientLangVersion = compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion(); if (compilation.IsNullableAnalysisEnabledIn(method)) { methodBodyForSemanticModel = NullableWalker.AnalyzeAndRewrite( compilation, method, methodBody, bodyBinder, nullableInitialState, // if language version is insufficient, we do not want to surface nullability diagnostics, // but we should still provide nullability information through the semantic model. isSufficientLangVersion ? diagnostics.DiagnosticBag : new DiagnosticBag(), createSnapshots: true, out snapshotManager, ref remappedSymbols); } else { NullableWalker.AnalyzeIfNeeded( compilation, method, methodBody, diagnostics.DiagnosticBag, useConstructorExitWarnings: true, nullableInitialState, getFinalNullableState: false, finalNullableState: out _); } forSemanticModel = new MethodBodySemanticModel.InitialState(syntaxNode, methodBodyForSemanticModel, bodyBinder, snapshotManager, remappedSymbols); switch (methodBody.Kind) { case BoundKind.ConstructorMethodBody: var constructor = (BoundConstructorMethodBody)methodBody; body = constructor.BlockBody ?? constructor.ExpressionBody; if (constructor.Initializer != null) { ReportCtorInitializerCycles(method, constructor.Initializer.Expression, compilationState, diagnostics); if (body == null) { body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer)); } else { body = new BoundBlock(constructor.Syntax, constructor.Locals, ImmutableArray.Create<BoundStatement>(constructor.Initializer, body)); originalBodyNested = true; } return body; } else { Debug.Assert(constructor.Locals.IsEmpty); } break; case BoundKind.NonConstructorMethodBody: var nonConstructor = (BoundNonConstructorMethodBody)methodBody; body = nonConstructor.BlockBody ?? nonConstructor.ExpressionBody; break; case BoundKind.Block: body = (BoundBlock)methodBody; break; default: throw ExceptionUtilities.UnexpectedValue(methodBody.Kind); } } else { var property = sourceMethod.AssociatedSymbol as SourcePropertySymbolBase; if ((object)property != null && property.IsAutoPropertyWithGetAccessor) { return MethodBodySynthesizer.ConstructAutoPropertyAccessorBody(sourceMethod); } return null; } } else if (method is SynthesizedInstanceConstructor ctor) { // Synthesized instance constructors may partially synthesize // their body var node = ctor.GetNonNullSyntaxNode(); var factory = new SyntheticBoundNodeFactory(ctor, node, compilationState, diagnostics); var stmts = ArrayBuilder<BoundStatement>.GetInstance(); ctor.GenerateMethodBodyStatements(factory, stmts, diagnostics); body = BoundBlock.SynthesizedNoLocals(node, stmts.ToImmutableAndFree()); } else { // synthesized methods should return their bound bodies body = null; } if (method.IsConstructor() && method.IsImplicitlyDeclared && nullableInitialState is object) { NullableWalker.AnalyzeIfNeeded( compilationState.Compilation, method, body ?? GetSynthesizedEmptyBody(method), diagnostics.DiagnosticBag, useConstructorExitWarnings: true, nullableInitialState, getFinalNullableState: false, finalNullableState: out _); } if (method.MethodKind == MethodKind.Destructor && body != null) { return MethodBodySynthesizer.ConstructDestructorBody(method, body); } var constructorInitializer = BindImplicitConstructorInitializerIfAny(method, compilationState, diagnostics); ImmutableArray<BoundStatement> statements; if (constructorInitializer == null) { if (body != null) { return body; } statements = ImmutableArray<BoundStatement>.Empty; } else if (body == null) { statements = ImmutableArray.Create(constructorInitializer); } else { statements = ImmutableArray.Create(constructorInitializer, body); originalBodyNested = true; } return BoundBlock.SynthesizedNoLocals(method.GetNonNullSyntaxNode(), statements); } private static BoundBlock GetSynthesizedEmptyBody(Symbol symbol) { return BoundBlock.SynthesizedNoLocals(symbol.GetNonNullSyntaxNode()); } private static BoundStatement BindImplicitConstructorInitializerIfAny(MethodSymbol method, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { Debug.Assert(!method.ContainingType.IsDelegateType()); // delegates have constructors but not constructor initializers if (method.MethodKind == MethodKind.Constructor && !method.IsExtern) { var compilation = method.DeclaringCompilation; var initializerInvocation = BindImplicitConstructorInitializer(method, diagnostics, compilation); if (initializerInvocation != null) { ReportCtorInitializerCycles(method, initializerInvocation, compilationState, diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. var constructorInitializer = new BoundExpressionStatement(initializerInvocation.Syntax, initializerInvocation) { WasCompilerGenerated = method.IsImplicitlyDeclared }; Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } } return null; } private static void ReportCtorInitializerCycles(MethodSymbol method, BoundExpression initializerInvocation, TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var ctorCall = initializerInvocation as BoundCall; if (ctorCall != null && !ctorCall.HasAnyErrors && ctorCall.Method != method && TypeSymbol.Equals(ctorCall.Method.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything2)) { // Detect and report indirect cycles in the ctor-initializer call graph. compilationState.ReportCtorInitializerCycles(method, ctorCall.Method, ctorCall.Syntax, diagnostics); } } /// <summary> /// Bind the implicit constructor initializer of a constructor symbol. /// </summary> /// <param name="constructor">Constructor method.</param> /// <param name="diagnostics">Accumulates errors (e.g. access "this" in constructor initializer).</param> /// <param name="compilation">Used to retrieve binder.</param> /// <returns>A bound expression for the constructor initializer call.</returns> internal static BoundExpression BindImplicitConstructorInitializer( MethodSymbol constructor, BindingDiagnosticBag diagnostics, CSharpCompilation compilation) { // Note that the base type can be null if we're compiling System.Object in source. NamedTypeSymbol containingType = constructor.ContainingType; NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; SourceMemberMethodSymbol sourceConstructor = constructor as SourceMemberMethodSymbol; Debug.Assert(sourceConstructor?.SyntaxNode is RecordDeclarationSyntax || ((ConstructorDeclarationSyntax)sourceConstructor?.SyntaxNode)?.Initializer == null); // The common case is that the type inherits directly from object. // Also, we might be trying to generate a constructor for an entirely compiler-generated class such // as a closure class; in that case it is vexing to try to find a suitable binder for the non-existing // constructor syntax so that we can do unnecessary overload resolution on the non-existing initializer! // Simply take the early out: bind directly to the parameterless object ctor rather than attempting // overload resolution. if ((object)baseType != null) { if (baseType.SpecialType == SpecialType.System_Object) { return GenerateBaseParameterlessConstructorInitializer(constructor, diagnostics); } else if (baseType.IsErrorType() || baseType.IsStatic) { // If the base type is bad and there is no initializer then we can just bail. // We have no expressions we need to analyze to report errors on. return null; } } if (containingType.IsStructType() || containingType.IsEnumType()) { return null; } else if (constructor is SynthesizedRecordCopyCtor copyCtor) { return GenerateBaseCopyConstructorInitializer(copyCtor, diagnostics); } // Now, in order to do overload resolution, we're going to need a binder. There are // two possible situations: // // class D1 : B { } // class D2 : B { D2(int x) { } } // // In the first case the binder needs to be the binder associated with // the *body* of D1 because if the base class ctor is protected, we need // to be inside the body of a derived class in order for it to be in the // accessibility domain of the protected base class ctor. // // In the second case the binder could be the binder associated with // the body of D2; since the implicit call to base() will have no arguments // there is no need to look up "x". Binder outerBinder; if ((object)sourceConstructor == null) { // The constructor is implicit. We need to get the binder for the body // of the enclosing class. CSharpSyntaxNode containerNode = constructor.GetNonNullSyntaxNode(); BinderFactory binderFactory = compilation.GetBinderFactory(containerNode.SyntaxTree); if (containerNode is RecordDeclarationSyntax recordDecl) { outerBinder = binderFactory.GetInRecordBodyBinder(recordDecl); } else { SyntaxToken bodyToken = GetImplicitConstructorBodyToken(containerNode); outerBinder = binderFactory.GetBinder(containerNode, bodyToken.Position); } } else { BinderFactory binderFactory = compilation.GetBinderFactory(sourceConstructor.SyntaxTree); switch (sourceConstructor.SyntaxNode) { case ConstructorDeclarationSyntax ctorDecl: // We have a ctor in source but no explicit constructor initializer. We can't just use the binder for the // type containing the ctor because the ctor might be marked unsafe. Use the binder for the parameter list // as an approximation - the extra symbols won't matter because there are no identifiers to bind. outerBinder = binderFactory.GetBinder(ctorDecl.ParameterList); break; case RecordDeclarationSyntax recordDecl: outerBinder = binderFactory.GetInRecordBodyBinder(recordDecl); break; default: throw ExceptionUtilities.Unreachable; } } // wrap in ConstructorInitializerBinder for appropriate errors // Handle scoping for possible pattern variables declared in the initializer Binder initializerBinder = outerBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.ConstructorInitializer, constructor); return initializerBinder.BindConstructorInitializer(null, constructor, diagnostics); } private static SyntaxToken GetImplicitConstructorBodyToken(CSharpSyntaxNode containerNode) { return ((BaseTypeDeclarationSyntax)containerNode).OpenBraceToken; } internal static BoundCall GenerateBaseParameterlessConstructorInitializer(MethodSymbol constructor, BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics; MethodSymbol baseConstructor = null; LookupResultKind resultKind = LookupResultKind.Viable; Location diagnosticsLocation = constructor.Locations.IsEmpty ? NoLocation.Singleton : constructor.Locations[0]; foreach (MethodSymbol ctor in baseType.InstanceConstructors) { if (ctor.ParameterCount == 0) { baseConstructor = ctor; break; } } // UNDONE: If this happens then something is deeply wrong. Should we give a better error? if ((object)baseConstructor == null) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, diagnosticsLocation, baseType, /*desired param count*/ 0); return null; } if (Binder.ReportUseSite(baseConstructor, diagnostics, diagnosticsLocation)) { return null; } // UNDONE: If this happens then something is deeply wrong. Should we give a better error? bool hasErrors = false; var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, constructor.ContainingAssembly); if (!AccessCheck.IsSymbolAccessible(baseConstructor, constructor.ContainingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadAccess, diagnosticsLocation, baseConstructor); resultKind = LookupResultKind.Inaccessible; hasErrors = true; } diagnostics.Add(diagnosticsLocation, useSiteInfo); CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode(); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; return new BoundCall( syntax: syntax, receiverOpt: receiver, method: baseConstructor, arguments: ImmutableArray<BoundExpression>.Empty, argumentNamesOpt: ImmutableArray<string>.Empty, argumentRefKindsOpt: ImmutableArray<RefKind>.Empty, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: ImmutableArray<int>.Empty, defaultArguments: BitVector.Empty, resultKind: resultKind, type: baseConstructor.ReturnType, hasErrors: hasErrors) { WasCompilerGenerated = true }; } private static BoundCall GenerateBaseCopyConstructorInitializer(SynthesizedRecordCopyCtor constructor, BindingDiagnosticBag diagnostics) { NamedTypeSymbol containingType = constructor.ContainingType; NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; Location diagnosticsLocation = constructor.Locations.FirstOrNone(); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, containingType.ContainingAssembly); MethodSymbol baseConstructor = SynthesizedRecordCopyCtor.FindCopyConstructor(baseType, containingType, ref useSiteInfo); if (baseConstructor is null) { diagnostics.Add(ErrorCode.ERR_NoCopyConstructorInBaseType, diagnosticsLocation, baseType); return null; } if (Binder.ReportUseSite(baseConstructor, diagnostics, diagnosticsLocation)) { return null; } diagnostics.Add(diagnosticsLocation, useSiteInfo); CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode(); BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType) { WasCompilerGenerated = true }; BoundExpression argument = new BoundParameter(syntax, constructor.Parameters[0]); return new BoundCall( syntax: syntax, receiverOpt: receiver, method: baseConstructor, arguments: ImmutableArray.Create(argument), argumentNamesOpt: default, argumentRefKindsOpt: default, isDelegateCall: false, expanded: false, invokedAsExtensionMethod: false, argsToParamsOpt: default, defaultArguments: default, resultKind: LookupResultKind.Viable, type: baseConstructor.ReturnType, hasErrors: false) { WasCompilerGenerated = true }; } private static Cci.DebugSourceDocument CreateDebugDocumentForFile(string normalizedPath) { return new Cci.DebugSourceDocument(normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp); } private static bool PassesFilter(Predicate<Symbol> filterOpt, Symbol symbol) { return (filterOpt == null) || filterOpt(symbol); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/SignatureOnlyParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Intended to be used to create ParameterSymbols for a SignatureOnlyMethodSymbol. /// </summary> internal sealed class SignatureOnlyParameterSymbol : ParameterSymbol { private readonly TypeWithAnnotations _type; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; private readonly bool _isParams; private readonly RefKind _refKind; public SignatureOnlyParameterSymbol( TypeWithAnnotations type, ImmutableArray<CustomModifier> refCustomModifiers, bool isParams, RefKind refKind) { Debug.Assert((object)type.Type != null); Debug.Assert(!refCustomModifiers.IsDefault); _type = type; _refCustomModifiers = refCustomModifiers; _isParams = isParams; _refKind = refKind; } public override TypeWithAnnotations TypeWithAnnotations { get { return _type; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } public override bool IsParams { get { return _isParams; } } public override RefKind RefKind { get { return _refKind; } } public override string Name { get { return ""; } } public override bool IsImplicitlyDeclared { get { return true; } } public override bool IsDiscard { get { return false; } } #region Not used by MethodSignatureComparer internal override bool IsMetadataIn { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsMetadataOut { get { throw ExceptionUtilities.Unreachable; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { throw ExceptionUtilities.Unreachable; } } public override int Ordinal { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsMetadataOptional { get { throw ExceptionUtilities.Unreachable; } } internal override ConstantValue ExplicitDefaultConstantValue { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIDispatchConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIUnknownConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerFilePath { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerLineNumber { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerMemberName { get { throw ExceptionUtilities.Unreachable; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { throw ExceptionUtilities.Unreachable; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<Location> Locations { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override AssemblySymbol ContainingAssembly { get { throw ExceptionUtilities.Unreachable; } } internal override ModuleSymbol ContainingModule { get { throw ExceptionUtilities.Unreachable; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable; internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable; #endregion Not used by MethodSignatureComparer public override bool Equals(Symbol obj, TypeCompareKind compareKind) { if ((object)this == obj) { return true; } var other = obj as SignatureOnlyParameterSymbol; return (object)other != null && TypeSymbol.Equals(_type.Type, other._type.Type, compareKind) && _type.CustomModifiers.Equals(other._type.CustomModifiers) && _refCustomModifiers.SequenceEqual(other._refCustomModifiers) && _isParams == other._isParams && _refKind == other._refKind; } public override int GetHashCode() { return Hash.Combine( _type.Type.GetHashCode(), Hash.Combine( Hash.CombineValues(_type.CustomModifiers), Hash.Combine( _isParams.GetHashCode(), _refKind.GetHashCode()))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Intended to be used to create ParameterSymbols for a SignatureOnlyMethodSymbol. /// </summary> internal sealed class SignatureOnlyParameterSymbol : ParameterSymbol { private readonly TypeWithAnnotations _type; private readonly ImmutableArray<CustomModifier> _refCustomModifiers; private readonly bool _isParams; private readonly RefKind _refKind; public SignatureOnlyParameterSymbol( TypeWithAnnotations type, ImmutableArray<CustomModifier> refCustomModifiers, bool isParams, RefKind refKind) { Debug.Assert((object)type.Type != null); Debug.Assert(!refCustomModifiers.IsDefault); _type = type; _refCustomModifiers = refCustomModifiers; _isParams = isParams; _refKind = refKind; } public override TypeWithAnnotations TypeWithAnnotations { get { return _type; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } } public override bool IsParams { get { return _isParams; } } public override RefKind RefKind { get { return _refKind; } } public override string Name { get { return ""; } } public override bool IsImplicitlyDeclared { get { return true; } } public override bool IsDiscard { get { return false; } } #region Not used by MethodSignatureComparer internal override bool IsMetadataIn { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsMetadataOut { get { throw ExceptionUtilities.Unreachable; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { throw ExceptionUtilities.Unreachable; } } public override int Ordinal { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsMetadataOptional { get { throw ExceptionUtilities.Unreachable; } } internal override ConstantValue ExplicitDefaultConstantValue { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIDispatchConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsIUnknownConstant { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerFilePath { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerLineNumber { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsCallerMemberName { get { throw ExceptionUtilities.Unreachable; } } internal override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { throw ExceptionUtilities.Unreachable; } } internal override ImmutableHashSet<string> NotNullIfParameterNotNull { get { throw ExceptionUtilities.Unreachable; } } public override Symbol ContainingSymbol { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<Location> Locations { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { throw ExceptionUtilities.Unreachable; } } public override AssemblySymbol ContainingAssembly { get { throw ExceptionUtilities.Unreachable; } } internal override ModuleSymbol ContainingModule { get { throw ExceptionUtilities.Unreachable; } } internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => throw ExceptionUtilities.Unreachable; internal override bool HasInterpolatedStringHandlerArgumentError => throw ExceptionUtilities.Unreachable; #endregion Not used by MethodSignatureComparer public override bool Equals(Symbol obj, TypeCompareKind compareKind) { if ((object)this == obj) { return true; } var other = obj as SignatureOnlyParameterSymbol; return (object)other != null && TypeSymbol.Equals(_type.Type, other._type.Type, compareKind) && _type.CustomModifiers.Equals(other._type.CustomModifiers) && _refCustomModifiers.SequenceEqual(other._refCustomModifiers) && _isParams == other._isParams && _refKind == other._refKind; } public override int GetHashCode() { return Hash.Combine( _type.Type.GetHashCode(), Hash.Combine( Hash.CombineValues(_type.CustomModifiers), Hash.Combine( _isParams.GetHashCode(), _refKind.GetHashCode()))); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/RuleSetDocumentExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal static class RuleSetDocumentExtensions { internal static void SetSeverity(this XDocument ruleSet, string analyzerId, string ruleId, ReportDiagnostic value) { var newAction = ConvertReportDiagnosticToAction(value); var rules = FindOrCreateRulesElement(ruleSet, analyzerId); var rule = FindOrCreateRuleElement(rules, ruleId); if (value == ReportDiagnostic.Default) { // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file. // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default' // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity // could still be decided by other factors such as project settings or a base ruleset file). rule.Remove(); } else { rule.Attribute("Action").Value = newAction; } var allMatchingRules = ruleSet.Root .Descendants("Rule") .Where(r => r.Attribute("Id").Value.Equals(ruleId)) .ToList(); foreach (var matchingRule in allMatchingRules) { if (value == ReportDiagnostic.Default) { // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file. // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default' // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity // could still be decided by other factors such as project settings or a base ruleset file). matchingRule.Remove(); } else { matchingRule.Attribute("Action").Value = newAction; } } } private static string ConvertReportDiagnosticToAction(ReportDiagnostic value) { switch (value) { case ReportDiagnostic.Default: return "Default"; case ReportDiagnostic.Error: return "Error"; case ReportDiagnostic.Warn: return "Warning"; case ReportDiagnostic.Info: return "Info"; case ReportDiagnostic.Hidden: return "Hidden"; case ReportDiagnostic.Suppress: return "None"; default: throw ExceptionUtilities.Unreachable; } } private static XElement FindOrCreateRuleElement(XElement rules, string id) { var ruleElement = rules .Elements("Rule") .FirstOrDefault(r => r.Attribute("Id").Value.Equals(id)); if (ruleElement == null) { ruleElement = new XElement("Rule", new XAttribute("Id", id), new XAttribute("Action", "Warning")); rules.Add(ruleElement); } return ruleElement; } private static XElement FindOrCreateRulesElement(XDocument ruleSetDocument, string analyzerID) { var rulesElement = ruleSetDocument.Root .Elements("Rules") .FirstOrDefault(r => r.Attribute("AnalyzerId").Value.Equals(analyzerID)); if (rulesElement == null) { rulesElement = new XElement("Rules", new XAttribute("AnalyzerId", analyzerID), new XAttribute("RuleNamespace", analyzerID)); ruleSetDocument.Root.Add(rulesElement); } return rulesElement; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal static class RuleSetDocumentExtensions { internal static void SetSeverity(this XDocument ruleSet, string analyzerId, string ruleId, ReportDiagnostic value) { var newAction = ConvertReportDiagnosticToAction(value); var rules = FindOrCreateRulesElement(ruleSet, analyzerId); var rule = FindOrCreateRuleElement(rules, ruleId); if (value == ReportDiagnostic.Default) { // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file. // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default' // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity // could still be decided by other factors such as project settings or a base ruleset file). rule.Remove(); } else { rule.Attribute("Action").Value = newAction; } var allMatchingRules = ruleSet.Root .Descendants("Rule") .Where(r => r.Attribute("Id").Value.Equals(ruleId)) .ToList(); foreach (var matchingRule in allMatchingRules) { if (value == ReportDiagnostic.Default) { // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file. // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default' // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity // could still be decided by other factors such as project settings or a base ruleset file). matchingRule.Remove(); } else { matchingRule.Attribute("Action").Value = newAction; } } } private static string ConvertReportDiagnosticToAction(ReportDiagnostic value) { switch (value) { case ReportDiagnostic.Default: return "Default"; case ReportDiagnostic.Error: return "Error"; case ReportDiagnostic.Warn: return "Warning"; case ReportDiagnostic.Info: return "Info"; case ReportDiagnostic.Hidden: return "Hidden"; case ReportDiagnostic.Suppress: return "None"; default: throw ExceptionUtilities.Unreachable; } } private static XElement FindOrCreateRuleElement(XElement rules, string id) { var ruleElement = rules .Elements("Rule") .FirstOrDefault(r => r.Attribute("Id").Value.Equals(id)); if (ruleElement == null) { ruleElement = new XElement("Rule", new XAttribute("Id", id), new XAttribute("Action", "Warning")); rules.Add(ruleElement); } return ruleElement; } private static XElement FindOrCreateRulesElement(XDocument ruleSetDocument, string analyzerID) { var rulesElement = ruleSetDocument.Root .Elements("Rules") .FirstOrDefault(r => r.Attribute("AnalyzerId").Value.Equals(analyzerID)); if (rulesElement == null) { rulesElement = new XElement("Rules", new XAttribute("AnalyzerId", analyzerID), new XAttribute("RuleNamespace", analyzerID)); ruleSetDocument.Root.Add(rulesElement); } return rulesElement; } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/RoslynActivityLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// Let people to inject <see cref="TraceSource"/> to monitor Roslyn activity /// /// Here, we don't technically use TraceSource as it is meant to be used. but just as an easy /// way to log data to listeners. /// /// this also involves creating string, boxing and etc. so, perf wise, it will impact VS quite a bit. /// this also won't collect trace from Roslyn OOP for now. only in proc activity /// </summary> internal static class RoslynActivityLogger { private static readonly object s_gate = new(); public static void SetLogger(TraceSource traceSource) { Contract.ThrowIfNull(traceSource); lock (s_gate) { // internally, it just uses our existing ILogger Logger.SetLogger(AggregateLogger.AddOrReplace(new TraceSourceLogger(traceSource), Logger.GetLogger(), l => (l as TraceSourceLogger)?.TraceSource == traceSource)); } } public static void RemoveLogger(TraceSource traceSource) { Contract.ThrowIfNull(traceSource); lock (s_gate) { // internally, it just uses our existing ILogger Logger.SetLogger(AggregateLogger.Remove(Logger.GetLogger(), l => (l as TraceSourceLogger)?.TraceSource == traceSource)); } } private class TraceSourceLogger : ILogger { private const int LogEventId = 0; private const int StartEventId = 1; private const int EndEventId = 2; private static readonly ImmutableDictionary<FunctionId, string> s_functionIdCache; public readonly TraceSource TraceSource; static TraceSourceLogger() { // build enum to string cache s_functionIdCache = Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>().ToImmutableDictionary(f => f, f => f.ToString()); } public TraceSourceLogger(TraceSource traceSource) => TraceSource = traceSource; public bool IsEnabled(FunctionId functionId) { // we log every roslyn activity return true; } public void Log(FunctionId functionId, LogMessage logMessage) => TraceSource.TraceData(TraceEventType.Verbose, LogEventId, s_functionIdCache[functionId], logMessage.GetMessage()); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => TraceSource.TraceData(TraceEventType.Verbose, StartEventId, s_functionIdCache[functionId], uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) => TraceSource.TraceData(TraceEventType.Verbose, EndEventId, s_functionIdCache[functionId], uniquePairId, cancellationToken.IsCancellationRequested, delta, logMessage.GetMessage()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Internal.Log; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// Let people to inject <see cref="TraceSource"/> to monitor Roslyn activity /// /// Here, we don't technically use TraceSource as it is meant to be used. but just as an easy /// way to log data to listeners. /// /// this also involves creating string, boxing and etc. so, perf wise, it will impact VS quite a bit. /// this also won't collect trace from Roslyn OOP for now. only in proc activity /// </summary> internal static class RoslynActivityLogger { private static readonly object s_gate = new(); public static void SetLogger(TraceSource traceSource) { Contract.ThrowIfNull(traceSource); lock (s_gate) { // internally, it just uses our existing ILogger Logger.SetLogger(AggregateLogger.AddOrReplace(new TraceSourceLogger(traceSource), Logger.GetLogger(), l => (l as TraceSourceLogger)?.TraceSource == traceSource)); } } public static void RemoveLogger(TraceSource traceSource) { Contract.ThrowIfNull(traceSource); lock (s_gate) { // internally, it just uses our existing ILogger Logger.SetLogger(AggregateLogger.Remove(Logger.GetLogger(), l => (l as TraceSourceLogger)?.TraceSource == traceSource)); } } private class TraceSourceLogger : ILogger { private const int LogEventId = 0; private const int StartEventId = 1; private const int EndEventId = 2; private static readonly ImmutableDictionary<FunctionId, string> s_functionIdCache; public readonly TraceSource TraceSource; static TraceSourceLogger() { // build enum to string cache s_functionIdCache = Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>().ToImmutableDictionary(f => f, f => f.ToString()); } public TraceSourceLogger(TraceSource traceSource) => TraceSource = traceSource; public bool IsEnabled(FunctionId functionId) { // we log every roslyn activity return true; } public void Log(FunctionId functionId, LogMessage logMessage) => TraceSource.TraceData(TraceEventType.Verbose, LogEventId, s_functionIdCache[functionId], logMessage.GetMessage()); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => TraceSource.TraceData(TraceEventType.Verbose, StartEventId, s_functionIdCache[functionId], uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) => TraceSource.TraceData(TraceEventType.Verbose, EndEventId, s_functionIdCache[functionId], uniquePairId, cancellationToken.IsCancellationRequested, delta, logMessage.GetMessage()); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/SimplifyBooleanExpression/CSharpSimplifyConditionalDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.SimplifyBooleanExpression; namespace Microsoft.CodeAnalysis.CSharp.SimplifyBooleanExpression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpSimplifyConditionalDiagnosticAnalyzer : AbstractSimplifyConditionalDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax> { protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override CommonConversion GetConversion(SemanticModel semanticModel, ExpressionSyntax node, CancellationToken cancellationToken) => semanticModel.GetConversion(node, cancellationToken).ToCommonConversion(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.SimplifyBooleanExpression; namespace Microsoft.CodeAnalysis.CSharp.SimplifyBooleanExpression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpSimplifyConditionalDiagnosticAnalyzer : AbstractSimplifyConditionalDiagnosticAnalyzer< SyntaxKind, ExpressionSyntax, ConditionalExpressionSyntax> { protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override CommonConversion GetConversion(SemanticModel semanticModel, ExpressionSyntax node, CancellationToken cancellationToken) => semanticModel.GetConversion(node, cancellationToken).ToCommonConversion(); } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_ReferenceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // All these tests came from the example at: // https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference public partial class CSharpRegexParserTests { [Fact] public void ReferenceTest0() { Test(@"@""[aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest1() { Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..68)"" Text=""(?&lt;duplicateWord&gt;\w+)\s\k&lt;duplicateWord&gt;\W(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""2"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest2() { Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""One"">One</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>abc</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""Two"">Two</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>xyz</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""((?&lt;One&gt;abc)\d+)?(?&lt;Two&gt;xyz)(.*)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""((?&lt;One&gt;abc)\d+)"" /> <Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" /> <Capture Name=""3"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""4"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> <Capture Name=""One"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""Two"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest3() { Test(@"@""(\w+)\s(\1)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest4() { Test(@"@""\Bqu\w+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <Text> <TextToken>qu</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest5() { Test(@"@""\bare\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>are</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest6() { Test(@"@""\G(\w+\s?\w*),?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest7() { Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?&lt;digit&gt;\d+)\D+(?&lt;digit&gt;\d+)?"" /> <Capture Name=""1"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> <Capture Name=""digit"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest8() { Test(@"@""(\s\d{4}(-(\d{4}&#124;present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>&amp;#124;present</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)+"" /> <Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)"" /> <Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&amp;#124;present))"" /> <Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&amp;#124;present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest9() { Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>present</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" /> <Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" /> <Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" /> <Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" /> <Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" /> <Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" /> <Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest10() { Test(@"@""^[0-9-[2468]]+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>2468</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest11() { Test(@"@""[a-z-[0-9]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest12() { Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>7F</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest13() { Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>FFFF</TextToken> </UnicodeEscape> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest14() { Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>d</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>w</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>m</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>o</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest15() { Test(@"@""((\w+(\s?)){2,}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest16() { Test(@"@""[a-z-[djp]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>djp</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest17() { Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..78)"" Text=""^[^&lt;&gt;]*(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*(?(Open)(?!))$"" /> <Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest18() { Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)+"" /> <Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest19() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest20() { Test(@"@""\d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest21() { Test(@"@""\d{1,2},""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest22() { Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>Saturday</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>Sunday</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>, </TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..55)"" Text=""(?&lt;!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" /> <Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest23() { Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>20</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?&lt;=\b20)\d{2}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest24() { Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest25() { Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*"" /> <Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest26() { Test(@"@""\b(?!un)\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>un</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest27() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest28() { Test(@"@""(?:\w+)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest29() { Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest30() { Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest31() { Test(@"@""(?'Close-Open'>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest32() { Test(@"@""[^<>]*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^&lt;&gt;]*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest33() { Test(@"@""\b\w+(?=\sis\b)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>is</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest34() { Test(@"@""[a-z-[m]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>m</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest35() { Test(@"@""^\D\d{1,5}\D*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""5"">5</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest36() { Test(@"@""[^0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest37() { Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" /> <Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest38() { Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" /> <Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" /> <Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" /> <Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest39() { Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.?!;:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" /> <Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest40() { Test(@"@""^.+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest41() { Test(@"@""[^o]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest42() { Test(@"@""\bth[^o]\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>th</TextToken> </Text> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest43() { Test(@"@""(\P{Sc})+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" /> <Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest44() { Test(@"@""[^\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest45() { Test(@"@""\b[A-Z]\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest46() { Test(@"@""\S+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest47() { Test(@"@""y\s""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest48() { Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest49() { Test(@"@""[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest50() { Test(@"@""[\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest51() { Test(@"@""[^aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest52() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest53() { Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lt</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lo</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lm</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest54() { Test(@"@""[^a-zA-Z_0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>_</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest55() { Test(@"@""\P{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest56() { Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" /> <Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest57() { Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" /> <Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest58() { Test(@"@""[0-9]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest59() { Test(@"@""\p{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest60() { Test(@"@""\b(\S+)\s?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest61() { Test(@"@""[^ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest62() { Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Z</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest63() { Test(@"@""(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest64() { Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>s</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" /> <Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest65() { Test(@"@""[ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest66() { Test(@"@""(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest67() { Test(@"@""(\w+)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest68() { Test(@"@""\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest69() { Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest70() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest71() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest72() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest73() { Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest74() { Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>p{Sc</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>}</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""amount"">amount</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?&lt;amount&gt;\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> <Capture Name=""amount"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest75() { Test(@"@""^(\w+\s?)+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" /> <Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest76() { Test(@"@""(?ix) d \w+ \s""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest77() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest78() { Test(@"@""\bthe\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>the</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest79() { Test(@"@""\b(?i:t)he\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>t</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken>he</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest80() { Test(@"@""^(\w+)\s(\d+)$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest81() { Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest82() { Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest83() { Test(@"@""(?s)^.+""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest84() { Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest85() { Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" /> <Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest86() { Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest87() { Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest88() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void ReferenceTest89() { Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Matches an entire sentence.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?&gt;\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" /> <Capture Name=""1"" Span=""[21..38)"" Text=""( (?&gt;\w+) ,?\s? )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest90() { Test(@"@""\bb\w+\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>b</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest91() { Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""(?&lt;=\d{1,2}\s)\w+,?\s\d{4}"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest92() { Test(@"@""\b(\w+\s*)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest93() { Test(@"@""((a+)(\1) ?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" /> <Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" /> <Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest94() { Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest95() { Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest96() { Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case-sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case-insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" /> <Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest97() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest98() { Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..58)"" Text=""\b(?&lt;n2&gt;\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> <Capture Name=""n2"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest99() { Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest100() { Test(@"@""\bgr(a|e)y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" /> <Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest101() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest102() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest103() { Test(@"@""\b91*9*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>9</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>1</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>9</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest104() { Test(@"@""\ban+\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <OneOrMoreQuantifier> <Text> <TextToken>n</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest105() { Test(@"@""\ban?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <ZeroOrOneQuantifier> <Text> <TextToken>n</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest106() { Test(@"@""\b\d+\,\d{3}\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>,</TextToken> </SimpleEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest107() { Test(@"@""\b\d{2,}\b\D+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest108() { Test(@"@""(00\s){2,4}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>00</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest109() { Test(@"@""\b\w*?oo\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>oo</TextToken> </Text> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest110() { Test(@"@""\b\w+?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest111() { Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>Console</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> <Text> <TextToken>Write</TextToken> </Text> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>Line</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" /> <Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" /> <Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest112() { Test(@"@""(System.)??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest113() { Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest114() { Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""10"">10</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" /> <Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest115() { Test(@"@""b.*([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>b</TextToken> </Text> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest116() { Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest117() { Test(@"@""(a?)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest118() { Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest119() { Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest120() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest121() { Test(@"@""(?<char>\w)\k<char>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?&lt;char&gt;\w)\k&lt;char&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> <Capture Name=""char"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest122() { Test(@"@""(?<2>\w)\k<2>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?&lt;2&gt;\w)\k&lt;2&gt;"" /> <Capture Name=""2"" Span=""[10..18)"" Text=""(?&lt;2&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest123() { Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?&lt;1&gt;a)(?&lt;1&gt;\1b)*"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest124() { Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" /> <Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" /> <Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest125() { Test(@"@""\bgr[ae]y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest126() { Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest127() { Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>{</TextToken> </SimpleEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>,</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>-</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>:</TextToken> </SimpleEscape> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>}</TextToken> </SimpleEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Looks for a composite format item.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" /> <Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" /> <Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" /> </Captures> </Tree>", RegexOptions.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // All these tests came from the example at: // https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference public partial class CSharpRegexParserTests { [Fact] public void ReferenceTest0() { Test(@"@""[aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest1() { Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..68)"" Text=""(?&lt;duplicateWord&gt;\w+)\s\k&lt;duplicateWord&gt;\W(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""2"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest2() { Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""One"">One</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>abc</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""Two"">Two</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>xyz</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""((?&lt;One&gt;abc)\d+)?(?&lt;Two&gt;xyz)(.*)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""((?&lt;One&gt;abc)\d+)"" /> <Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" /> <Capture Name=""3"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""4"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> <Capture Name=""One"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""Two"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest3() { Test(@"@""(\w+)\s(\1)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest4() { Test(@"@""\Bqu\w+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <Text> <TextToken>qu</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest5() { Test(@"@""\bare\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>are</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest6() { Test(@"@""\G(\w+\s?\w*),?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest7() { Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?&lt;digit&gt;\d+)\D+(?&lt;digit&gt;\d+)?"" /> <Capture Name=""1"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> <Capture Name=""digit"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest8() { Test(@"@""(\s\d{4}(-(\d{4}&#124;present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>&amp;#124;present</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)+"" /> <Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)"" /> <Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&amp;#124;present))"" /> <Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&amp;#124;present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest9() { Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>present</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" /> <Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" /> <Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" /> <Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" /> <Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" /> <Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" /> <Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest10() { Test(@"@""^[0-9-[2468]]+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>2468</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest11() { Test(@"@""[a-z-[0-9]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest12() { Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>7F</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest13() { Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>FFFF</TextToken> </UnicodeEscape> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest14() { Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>d</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>w</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>m</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>o</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest15() { Test(@"@""((\w+(\s?)){2,}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest16() { Test(@"@""[a-z-[djp]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>djp</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest17() { Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..78)"" Text=""^[^&lt;&gt;]*(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*(?(Open)(?!))$"" /> <Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest18() { Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)+"" /> <Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest19() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest20() { Test(@"@""\d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest21() { Test(@"@""\d{1,2},""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest22() { Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>Saturday</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>Sunday</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>, </TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..55)"" Text=""(?&lt;!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" /> <Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest23() { Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>20</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?&lt;=\b20)\d{2}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest24() { Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest25() { Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*"" /> <Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest26() { Test(@"@""\b(?!un)\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>un</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest27() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest28() { Test(@"@""(?:\w+)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest29() { Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest30() { Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest31() { Test(@"@""(?'Close-Open'>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest32() { Test(@"@""[^<>]*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^&lt;&gt;]*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest33() { Test(@"@""\b\w+(?=\sis\b)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>is</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest34() { Test(@"@""[a-z-[m]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>m</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest35() { Test(@"@""^\D\d{1,5}\D*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""5"">5</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest36() { Test(@"@""[^0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest37() { Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" /> <Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest38() { Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" /> <Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" /> <Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" /> <Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest39() { Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.?!;:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" /> <Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest40() { Test(@"@""^.+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest41() { Test(@"@""[^o]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest42() { Test(@"@""\bth[^o]\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>th</TextToken> </Text> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest43() { Test(@"@""(\P{Sc})+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" /> <Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest44() { Test(@"@""[^\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest45() { Test(@"@""\b[A-Z]\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest46() { Test(@"@""\S+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest47() { Test(@"@""y\s""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest48() { Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest49() { Test(@"@""[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest50() { Test(@"@""[\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest51() { Test(@"@""[^aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest52() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest53() { Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lt</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lo</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lm</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest54() { Test(@"@""[^a-zA-Z_0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>_</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest55() { Test(@"@""\P{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest56() { Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" /> <Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest57() { Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" /> <Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest58() { Test(@"@""[0-9]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest59() { Test(@"@""\p{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest60() { Test(@"@""\b(\S+)\s?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest61() { Test(@"@""[^ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest62() { Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Z</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest63() { Test(@"@""(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest64() { Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>s</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" /> <Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest65() { Test(@"@""[ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest66() { Test(@"@""(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest67() { Test(@"@""(\w+)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest68() { Test(@"@""\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest69() { Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest70() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest71() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest72() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest73() { Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest74() { Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>p{Sc</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>}</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""amount"">amount</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?&lt;amount&gt;\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> <Capture Name=""amount"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest75() { Test(@"@""^(\w+\s?)+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" /> <Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest76() { Test(@"@""(?ix) d \w+ \s""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest77() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest78() { Test(@"@""\bthe\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>the</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest79() { Test(@"@""\b(?i:t)he\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>t</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken>he</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest80() { Test(@"@""^(\w+)\s(\d+)$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest81() { Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest82() { Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest83() { Test(@"@""(?s)^.+""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest84() { Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest85() { Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" /> <Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest86() { Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest87() { Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest88() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void ReferenceTest89() { Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Matches an entire sentence.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?&gt;\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" /> <Capture Name=""1"" Span=""[21..38)"" Text=""( (?&gt;\w+) ,?\s? )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest90() { Test(@"@""\bb\w+\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>b</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest91() { Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""(?&lt;=\d{1,2}\s)\w+,?\s\d{4}"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest92() { Test(@"@""\b(\w+\s*)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest93() { Test(@"@""((a+)(\1) ?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" /> <Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" /> <Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest94() { Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest95() { Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest96() { Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case-sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case-insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" /> <Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest97() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest98() { Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..58)"" Text=""\b(?&lt;n2&gt;\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> <Capture Name=""n2"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest99() { Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest100() { Test(@"@""\bgr(a|e)y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" /> <Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest101() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest102() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest103() { Test(@"@""\b91*9*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>9</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>1</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>9</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest104() { Test(@"@""\ban+\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <OneOrMoreQuantifier> <Text> <TextToken>n</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest105() { Test(@"@""\ban?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <ZeroOrOneQuantifier> <Text> <TextToken>n</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest106() { Test(@"@""\b\d+\,\d{3}\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>,</TextToken> </SimpleEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest107() { Test(@"@""\b\d{2,}\b\D+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest108() { Test(@"@""(00\s){2,4}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>00</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest109() { Test(@"@""\b\w*?oo\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>oo</TextToken> </Text> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest110() { Test(@"@""\b\w+?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest111() { Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>Console</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> <Text> <TextToken>Write</TextToken> </Text> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>Line</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" /> <Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" /> <Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest112() { Test(@"@""(System.)??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest113() { Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest114() { Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""10"">10</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" /> <Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest115() { Test(@"@""b.*([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>b</TextToken> </Text> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest116() { Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest117() { Test(@"@""(a?)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest118() { Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest119() { Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest120() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest121() { Test(@"@""(?<char>\w)\k<char>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?&lt;char&gt;\w)\k&lt;char&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> <Capture Name=""char"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest122() { Test(@"@""(?<2>\w)\k<2>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?&lt;2&gt;\w)\k&lt;2&gt;"" /> <Capture Name=""2"" Span=""[10..18)"" Text=""(?&lt;2&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest123() { Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?&lt;1&gt;a)(?&lt;1&gt;\1b)*"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest124() { Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" /> <Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" /> <Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest125() { Test(@"@""\bgr[ae]y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest126() { Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest127() { Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>{</TextToken> </SimpleEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>,</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>-</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>:</TextToken> </SimpleEscape> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>}</TextToken> </SimpleEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Looks for a composite format item.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" /> <Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" /> <Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" /> </Captures> </Tree>", RegexOptions.None); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectChanges.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; namespace Microsoft.CodeAnalysis { public struct ProjectChanges { private readonly Project _newProject; private readonly Project _oldProject; internal ProjectChanges(Project newProject, Project oldProject) { _newProject = newProject; _oldProject = oldProject; } public ProjectId ProjectId => _newProject.Id; public Project OldProject => _oldProject; public Project NewProject => _newProject; public IEnumerable<ProjectReference> GetAddedProjectReferences() { var oldRefs = new HashSet<ProjectReference>(_oldProject.ProjectReferences); foreach (var reference in _newProject.ProjectReferences) { if (!oldRefs.Contains(reference)) { yield return reference; } } } public IEnumerable<ProjectReference> GetRemovedProjectReferences() { var newRefs = new HashSet<ProjectReference>(_newProject.ProjectReferences); foreach (var reference in _oldProject.ProjectReferences) { if (!newRefs.Contains(reference)) { yield return reference; } } } public IEnumerable<MetadataReference> GetAddedMetadataReferences() { var oldMetadata = new HashSet<MetadataReference>(_oldProject.MetadataReferences); foreach (var metadata in _newProject.MetadataReferences) { if (!oldMetadata.Contains(metadata)) { yield return metadata; } } } public IEnumerable<MetadataReference> GetRemovedMetadataReferences() { var newMetadata = new HashSet<MetadataReference>(_newProject.MetadataReferences); foreach (var metadata in _oldProject.MetadataReferences) { if (!newMetadata.Contains(metadata)) { yield return metadata; } } } public IEnumerable<AnalyzerReference> GetAddedAnalyzerReferences() { var oldAnalyzerReferences = new HashSet<AnalyzerReference>(_oldProject.AnalyzerReferences); foreach (var analyzerReference in _newProject.AnalyzerReferences) { if (!oldAnalyzerReferences.Contains(analyzerReference)) { yield return analyzerReference; } } } public IEnumerable<AnalyzerReference> GetRemovedAnalyzerReferences() { var newAnalyzerReferences = new HashSet<AnalyzerReference>(_newProject.AnalyzerReferences); foreach (var analyzerReference in _oldProject.AnalyzerReferences) { if (!newAnalyzerReferences.Contains(analyzerReference)) { yield return analyzerReference; } } } /// <summary> /// Get <see cref="DocumentId"/>s of added documents in the order they appear in <see cref="Project.DocumentIds"/> of the <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedDocuments() => _newProject.State.DocumentStates.GetAddedStateIds(_oldProject.State.DocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of added dditional documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetAddedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of added analyzer config documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetAddedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedDocuments() => GetChangedDocuments(onlyGetDocumentsWithTextChanges: false); /// <summary> /// Get changed documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// When <paramref name="onlyGetDocumentsWithTextChanges"/> is true, only get documents with text changes (we only check text source, not actual content); /// otherwise get documents with any changes i.e. <see cref="ParseOptions"/>, <see cref="SourceCodeKind"/> and file path. /// </summary> public IEnumerable<DocumentId> GetChangedDocuments(bool onlyGetDocumentsWithTextChanges) => GetChangedDocuments(onlyGetDocumentsWithTextChanges, ignoreUnchangeableDocuments: false); internal IEnumerable<DocumentId> GetChangedDocuments(bool onlyGetDocumentsWithTextChanges, bool ignoreUnchangeableDocuments) => _newProject.State.DocumentStates.GetChangedStateIds(_oldProject.State.DocumentStates, onlyGetDocumentsWithTextChanges, ignoreUnchangeableDocuments); /// <summary> /// Get <see cref="DocumentId"/>s of additional documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetChangedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of analyzer config documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetChangedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedDocuments() => _newProject.State.DocumentStates.GetRemovedStateIds(_oldProject.State.DocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed additional documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetRemovedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed analyzer config documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetRemovedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Diagnostics; namespace Microsoft.CodeAnalysis { public struct ProjectChanges { private readonly Project _newProject; private readonly Project _oldProject; internal ProjectChanges(Project newProject, Project oldProject) { _newProject = newProject; _oldProject = oldProject; } public ProjectId ProjectId => _newProject.Id; public Project OldProject => _oldProject; public Project NewProject => _newProject; public IEnumerable<ProjectReference> GetAddedProjectReferences() { var oldRefs = new HashSet<ProjectReference>(_oldProject.ProjectReferences); foreach (var reference in _newProject.ProjectReferences) { if (!oldRefs.Contains(reference)) { yield return reference; } } } public IEnumerable<ProjectReference> GetRemovedProjectReferences() { var newRefs = new HashSet<ProjectReference>(_newProject.ProjectReferences); foreach (var reference in _oldProject.ProjectReferences) { if (!newRefs.Contains(reference)) { yield return reference; } } } public IEnumerable<MetadataReference> GetAddedMetadataReferences() { var oldMetadata = new HashSet<MetadataReference>(_oldProject.MetadataReferences); foreach (var metadata in _newProject.MetadataReferences) { if (!oldMetadata.Contains(metadata)) { yield return metadata; } } } public IEnumerable<MetadataReference> GetRemovedMetadataReferences() { var newMetadata = new HashSet<MetadataReference>(_newProject.MetadataReferences); foreach (var metadata in _oldProject.MetadataReferences) { if (!newMetadata.Contains(metadata)) { yield return metadata; } } } public IEnumerable<AnalyzerReference> GetAddedAnalyzerReferences() { var oldAnalyzerReferences = new HashSet<AnalyzerReference>(_oldProject.AnalyzerReferences); foreach (var analyzerReference in _newProject.AnalyzerReferences) { if (!oldAnalyzerReferences.Contains(analyzerReference)) { yield return analyzerReference; } } } public IEnumerable<AnalyzerReference> GetRemovedAnalyzerReferences() { var newAnalyzerReferences = new HashSet<AnalyzerReference>(_newProject.AnalyzerReferences); foreach (var analyzerReference in _oldProject.AnalyzerReferences) { if (!newAnalyzerReferences.Contains(analyzerReference)) { yield return analyzerReference; } } } /// <summary> /// Get <see cref="DocumentId"/>s of added documents in the order they appear in <see cref="Project.DocumentIds"/> of the <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedDocuments() => _newProject.State.DocumentStates.GetAddedStateIds(_oldProject.State.DocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of added dditional documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetAddedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of added analyzer config documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetAddedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetAddedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedDocuments() => GetChangedDocuments(onlyGetDocumentsWithTextChanges: false); /// <summary> /// Get changed documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// When <paramref name="onlyGetDocumentsWithTextChanges"/> is true, only get documents with text changes (we only check text source, not actual content); /// otherwise get documents with any changes i.e. <see cref="ParseOptions"/>, <see cref="SourceCodeKind"/> and file path. /// </summary> public IEnumerable<DocumentId> GetChangedDocuments(bool onlyGetDocumentsWithTextChanges) => GetChangedDocuments(onlyGetDocumentsWithTextChanges, ignoreUnchangeableDocuments: false); internal IEnumerable<DocumentId> GetChangedDocuments(bool onlyGetDocumentsWithTextChanges, bool ignoreUnchangeableDocuments) => _newProject.State.DocumentStates.GetChangedStateIds(_oldProject.State.DocumentStates, onlyGetDocumentsWithTextChanges, ignoreUnchangeableDocuments); /// <summary> /// Get <see cref="DocumentId"/>s of additional documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetChangedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of analyzer config documents with any changes (textual and non-textual) /// in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="NewProject"/>. /// </summary> public IEnumerable<DocumentId> GetChangedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetChangedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedDocuments() => _newProject.State.DocumentStates.GetRemovedStateIds(_oldProject.State.DocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed additional documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedAdditionalDocuments() => _newProject.State.AdditionalDocumentStates.GetRemovedStateIds(_oldProject.State.AdditionalDocumentStates); /// <summary> /// Get <see cref="DocumentId"/>s of removed analyzer config documents in the order they appear in <see cref="Project.DocumentIds"/> of <see cref="OldProject"/>. /// </summary> public IEnumerable<DocumentId> GetRemovedAnalyzerConfigDocuments() => _newProject.State.AnalyzerConfigDocumentStates.GetRemovedStateIds(_oldProject.State.AnalyzerConfigDocumentStates); } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/SyntaxKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // A subset of the VB compiler SyntaxKind enum, containing // just those values recognized by the signature parser. internal enum SyntaxKind { None, OfKeyword, ByValKeyword, ByRefKeyword, BooleanKeyword, CharKeyword, SByteKeyword, ByteKeyword, ShortKeyword, UShortKeyword, IntegerKeyword, UIntegerKeyword, LongKeyword, ULongKeyword, SingleKeyword, DoubleKeyword, StringKeyword, ObjectKeyword, DecimalKeyword, DateKeyword, } private static ImmutableDictionary<string, SyntaxKind> GetKeywordKinds(StringComparer comparer) { var builder = ImmutableDictionary.CreateBuilder<string, SyntaxKind>(comparer); builder.Add("of", SyntaxKind.OfKeyword); builder.Add("byval", SyntaxKind.ByValKeyword); builder.Add("byref", SyntaxKind.ByRefKeyword); builder.Add("boolean", SyntaxKind.BooleanKeyword); builder.Add("char", SyntaxKind.CharKeyword); builder.Add("sbyte", SyntaxKind.SByteKeyword); builder.Add("byte", SyntaxKind.ByteKeyword); builder.Add("short", SyntaxKind.ShortKeyword); builder.Add("ushort", SyntaxKind.UShortKeyword); builder.Add("integer", SyntaxKind.IntegerKeyword); builder.Add("uinteger", SyntaxKind.UIntegerKeyword); builder.Add("long", SyntaxKind.LongKeyword); builder.Add("ulong", SyntaxKind.ULongKeyword); builder.Add("single", SyntaxKind.SingleKeyword); builder.Add("double", SyntaxKind.DoubleKeyword); builder.Add("string", SyntaxKind.StringKeyword); builder.Add("object", SyntaxKind.ObjectKeyword); builder.Add("decimal", SyntaxKind.DecimalKeyword); builder.Add("date", SyntaxKind.DateKeyword); return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // A subset of the VB compiler SyntaxKind enum, containing // just those values recognized by the signature parser. internal enum SyntaxKind { None, OfKeyword, ByValKeyword, ByRefKeyword, BooleanKeyword, CharKeyword, SByteKeyword, ByteKeyword, ShortKeyword, UShortKeyword, IntegerKeyword, UIntegerKeyword, LongKeyword, ULongKeyword, SingleKeyword, DoubleKeyword, StringKeyword, ObjectKeyword, DecimalKeyword, DateKeyword, } private static ImmutableDictionary<string, SyntaxKind> GetKeywordKinds(StringComparer comparer) { var builder = ImmutableDictionary.CreateBuilder<string, SyntaxKind>(comparer); builder.Add("of", SyntaxKind.OfKeyword); builder.Add("byval", SyntaxKind.ByValKeyword); builder.Add("byref", SyntaxKind.ByRefKeyword); builder.Add("boolean", SyntaxKind.BooleanKeyword); builder.Add("char", SyntaxKind.CharKeyword); builder.Add("sbyte", SyntaxKind.SByteKeyword); builder.Add("byte", SyntaxKind.ByteKeyword); builder.Add("short", SyntaxKind.ShortKeyword); builder.Add("ushort", SyntaxKind.UShortKeyword); builder.Add("integer", SyntaxKind.IntegerKeyword); builder.Add("uinteger", SyntaxKind.UIntegerKeyword); builder.Add("long", SyntaxKind.LongKeyword); builder.Add("ulong", SyntaxKind.ULongKeyword); builder.Add("single", SyntaxKind.SingleKeyword); builder.Add("double", SyntaxKind.DoubleKeyword); builder.Add("string", SyntaxKind.StringKeyword); builder.Add("object", SyntaxKind.ObjectKeyword); builder.Add("decimal", SyntaxKind.DecimalKeyword); builder.Add("date", SyntaxKind.DateKeyword); return builder.ToImmutable(); } } }
-1
dotnet/roslyn
54,966
Fix 'line separators' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T01:21:43Z
2021-07-20T07:17:27Z
21d77e7a48ec8b7556b708d64cb5a63e88f3a255
28191eef78568088a332a435dcd734fad1bd4fbf
Fix 'line separators' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Mocks/TestAdditionalText.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Roslyn.Test.Utilities { public sealed class TestAdditionalText : AdditionalText { private readonly SourceText _text; public TestAdditionalText(string path, SourceText text) { Path = path; _text = text; } public TestAdditionalText(string text = "", Encoding? encoding = null, string path = "dummy") : this(path, new StringText(text, encoding)) { } public override string Path { get; } public override SourceText GetText(CancellationToken cancellationToken = default) => _text; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Roslyn.Test.Utilities { public sealed class TestAdditionalText : AdditionalText { private readonly SourceText _text; public TestAdditionalText(string path, SourceText text) { Path = path; _text = text; } public TestAdditionalText(string text = "", Encoding? encoding = null, string path = "dummy") : this(path, new StringText(text, encoding)) { } public override string Path { get; } public override SourceText GetText(CancellationToken cancellationToken = default) => _text; } }
-1